1. 程式人生 > >Android URLConnection發送Get請求 HttpGet封裝

Android URLConnection發送Get請求 HttpGet封裝

返回 turn ava cep obj pub rac stack upn

一.使用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。

    註意關閉順序:關閉要與new的順序反過來。

    抽象理解:下班回家睡覺 先進入小區,再進入家,再進入臥室;上班時就要先走出臥室,再走出家,最後走出小區。要遵循規則,不能使用閃現技能直接走出小區。

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){
                Object[] objects=headers.entrySet().toArray();
                
for (Object o: objects) { String[] strings=o.toString().split("="); connection.setRequestProperty(strings[0],strings[1]); } } //獲取響應信息 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.在子線程中訪問網絡。

Android URLConnection發送Get請求 HttpGet封裝