【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();

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