网络请求的2种方式

1.httpclient

用as编程在gradle文件中配置

useLibrary 'org.apache.http.legacy'
Google不推荐使用了

  
                HttpClient httpCient = new DefaultHttpClient();
         
               HttpGet httpGet = new HttpGet("http://www.baidu.com");
                 
                 try {
             
                    HttpResponse httpResponse = httpCient.execute(httpGet);
                    
                     if (httpResponse.getStatusLine().getStatusCode() == 200) {
                 
                       HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串
                         Message message = new Message();
                         message.what = SHOW_RESPONSE;
                        message.obj = response.toString();
                         handler.sendMessage(message);
                     }
网络请求需要放在子线程中

第二种: 

HttpURLConnection

           URL url = new URL("http://www.baidu.com");
            
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            if(200 == urlConnection.getResponseCode()){
                //得到输入流
                InputStream is =urlConnection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while(-1 != (len = is.read(buffer))){
                    baos.write(buffer,0,len);
                    baos.flush();
                }
                return baos.toString("utf-8");
volley框架的使用:

RequestQueue mQueue = Volley.newRequestQueue(context);  


StringRequest stringRequest = new StringRequest("http://www.baidu.com",  
                        new Response.Listener() {  
                            @Override  
                            public void onResponse(String response) {  
                                Log.d("TAG", response);  
                            }  
                        }, new Response.ErrorListener() {  
                            @Override  
                            public void onErrorResponse(VolleyError error) {  
                                Log.e("TAG", error.getMessage(), error);  
                            }  
                        });  
mQueue.add(stringRequest);





你可能感兴趣的:(菜鸟级别)