Android URLConnection发送Get请求 HttpGet封装

一.使用URLConnection发送Get请求

1.与服务器建立连接:

URLConnection connection=new URL(“https://www.baidu.com/”).openConnection();

2.设置请求头(Cookie亦可通过请求头设置):

connection.setRequestProperty(“Referer”,“https://www.baidu.com/);
connection.setRequestProperty(“Cookie”,“BIDUPSID=844B9321236FFD30C304AE4CCEE0602A;BD_UPN=12314753”);

3.获取响应信息:

(1):建议使用StringBuilder拼接字符串;

(2):如果new了流对象不要忘记close。

StringBuilder response=new StringBuilder();
	
            InputStream is=connection.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String str;
            while ((str=br.readLine())!=null){
                response.append(str);
            }
            br.close();
            is.close();

return response.toString();

 

二.HttpGet封装

源码:

    static public String  HttpGet(String url,Map headers){

        try {
            //打开连接
            URLConnection connection=new URL(url).openConnection();

            //设置请求头
            if(headers!=null){
                Set<Map.Entry> set=headers.entrySet();
                for (Map.Entry entry:set) {
                    connection.setRequestProperty(entry.getKey().toString,entry.getValue().toString);
                }
            }
            //获取响应信息
            StringBuilder response=new StringBuilder();

            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str=br.readLine())!=null){
                response.append(str);
            }
            br.close();

            //返回结果
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

调用:

Map headers=new HashMap();
headers.put("Referer","https://www.baidu.com/");
headers.put("Cookie","BIDUPSID=844B9321236FFD30C304AE4CCEE0602A;BD_UPN=12314753")
HttpGet("https://www.baidu.com/",headers);

 

三.android网络请求两大要素

1.申请网络权限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>;

2.在子线程中访问网络。

posted @ 2017-11-10 20:42  BadAmbition  阅读(223)  评论(0)    收藏  举报