Android URLConnection發送Get請求 HttpGet封裝

來源:互聯網
上載者:User

標籤:static   blog   建立   cee   服務   ash   catch   android   obj   

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.