【Android記錄】HttpURLConnection的使用

/**
 * 需要開啓線程發起網絡請求
 */
private void sendRequestWithHttpURLConnection(){

    new Thread(new Runnable() {

        @Override
        public void run() {

            HttpURLConnection connection=null;
            BufferedReader reader=null;

            try{

                URL url=new URL("http://www.baidu.com");
                connection=(HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");//請求類型表示從服務器得到數據
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);

                InputStream in=connection.getInputStream();

                //對獲取到的輸入流進行讀取(服務器返回的流)
                reader=new BufferedReader(new InputStreamReader(in));
                StringBuilder response=new StringBuilder();
                String line;
                while ((line=reader.readLine())!=null){
                    response.append(line);
                }

                //顯示結果,由於是在線程之中,需要新開一個ui線程對ui進行操作
                showResponse(response.toString());


            }catch (Exception e){

                e.printStackTrace();

            }finally {

                if(reader!=null){
                    try{
                        reader.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }

                if (connection!=null){
                    connection.disconnect();
                }

            }
        }
    }).start();

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章