码迷,mamicode.com
首页 > 编程语言 > 详细

java访问url

时间:2016-08-01 19:09:11      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

 1     /**
 2      * 根据URL地址和参数,获取返回数据
 3      */
 4     private String login_postMethod(String url, String jsonParam) throws IOException {
 5         URL postUrl = new URL(url);
 6         HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
 7         connection.setDoOutput(true);
 8         connection.setDoInput(true);
 9         connection.setRequestMethod("POST");
10         connection.setUseCaches(false);
11         connection.setInstanceFollowRedirects(true);
12         connection.setRequestProperty("Content-Type", "application/json"); // 设置参数内容类型
13         connection.setRequestProperty("Connection", "Keep-Alive");
14         connection.connect();
15 
16         DataOutputStream out = new DataOutputStream(connection.getOutputStream());
17         out.writeBytes(jsonParam);
18         out.flush();
19         out.close();
20 
21         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //设置返回结果的编码格式
22         responseCookie = connection.getHeaderField("Set-Cookie");// 取到所用的Cookie
23 
24         // 获取请求返回结果
25         String result = "";
26         String line;
27         while ((line = reader.readLine()) != null) {
28             result += line;
29         }
30 
31         reader.close();
32         connection.disconnect();
33 
34         return result ;
35     }
    /**
     * 根据URL地址和参数,获取返回数据
     */
    private String searchData_postMethod(String url, String jsonParam) throws IOException {
        URL postUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setRequestProperty("Cookie", responseCookie); // 设置login时返回的cookie
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.connect();

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(jsonParam);
        out.flush();
        out.close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

        // 获取请求返回结果
        String result = "";
        String line;
        while ((line = reader.readLine()) != null) {
            result += line;
        }

        reader.close();
        connection.disconnect();

        return result ;
    }

 

java访问url

标签:

原文地址:http://www.cnblogs.com/zj0208/p/5726952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!