/** * 需要开启线程发起网络请求 */ 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(); }
【Android记录】HttpURLConnection的使用
最新推荐文章于 2024-07-07 21:30:19 发布