zoukankan      html  css  js  c++  java
  • HttpURLConnection和Apach HttpClient的对比及取舍

    1,安卓官方对DefaultHttpClient的说明是:

    Prefer HttpURLConnection for new code

    Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling. Apache HTTP client has fewer bugs in Android 2.2 (Froyo) and earlier releases. For Android 2.3 (Gingerbread) and later, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. See the Android Developers Blog for a comparison of the two HTTP clients.

    2,网上有人对比了二者的性能:

    测试代码:

    1.import java.io.BufferedReader;  
    2.import java.io.IOException;  
    3.import java.io.InputStream;  
    4.import java.io.InputStreamReader;  
    5.import java.net.HttpURLConnection;  
    6.import java.net.MalformedURLException;  
    7.import java.net.URL;  
    8.  
    9.import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
    10.import org.apache.commons.httpclient.HttpClient;  
    11.import org.apache.commons.httpclient.HttpException;  
    12.import org.apache.commons.httpclient.HttpStatus;  
    13.import org.apache.commons.httpclient.methods.GetMethod;  
    14.import org.apache.commons.httpclient.params.HttpMethodParams;  
    15.  
    16.public class HttpClientTest {  
    17.  
    18.    private static String link = "http://www.baidu.com";  
    19.  
    20.    public static void main(String[] args) {  
    21.        long a = System.currentTimeMillis();  
    22.        useHttpURlConnection();  
    23.        long b = System.currentTimeMillis();  
    24.        System.out.println("use httpurlconnection: "+(b-a));  
    25.        long c = System.currentTimeMillis();  
    26.        useHttpClient();  
    27.        long d = System.currentTimeMillis();  
    28.        System.out.println("use httpclient: "+(d-c));  
    29.    }  
    30.      
    31.    public static void useHttpURlConnection(){  
    32.        HttpURLConnection conn = null;  
    33.        URL url = null;  
    34.        String result = "";  
    35.        try {  
    36.            url = new java.net.URL(link);  
    37.            conn = (HttpURLConnection) url.openConnection();  
    38.            conn.setConnectTimeout(10000);  
    39.            conn.connect();  
    40.  
    41.            InputStream urlStream = conn.getInputStream();  
    42.            BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream));  
    43.            String s = "";  
    44.            while ((s = reader.readLine()) != null) {  
    45.                result += s;  
    46.            }  
    47.            System.out.println(result);  
    48.            reader.close();  
    49.            urlStream.close();  
    50.            conn.disconnect();  
    51.        } catch (MalformedURLException e) {  
    52.            e.printStackTrace();  
    53.        } catch (IOException e) {  
    54.            e.printStackTrace();  
    55.        } catch(Exception e){  
    56.            e.printStackTrace();  
    57.        }  
    58.    }  
    59.  
    60.    public static void useHttpClient(){  
    61.        HttpClient client = new HttpClient();  
    62.        GetMethod method = new GetMethod(link);  
    63.        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
    64.                new DefaultHttpMethodRetryHandler(3, false));  
    65.        try {  
    66.            int statusCode = client.executeMethod(method);  
    67.  
    68.            if (statusCode != HttpStatus.SC_OK) {  
    69.                System.err.println("Method failed: " + method.getStatusLine());  
    70.            }  
    71.            byte[] responseBody = method.getResponseBody();  
    72.            System.out.println(new String(responseBody));  
    73.        } catch (HttpException e) {  
    74.            System.err.println("Fatal protocol violation: " + e.getMessage());  
    75.            e.printStackTrace();  
    76.        } catch (IOException e) {  
    77.            System.err.println("Fatal transport error: " + e.getMessage());  
    78.            e.printStackTrace();  
    79.        } finally {  
    80.            method.releaseConnection();  
    81.        }  
    82.    }  
    83.}  

    测试结果:

    use httpurlconnection: 47

    use httpclient: 641

    3,但是HttpClient的使用确是方便了很多。下面是一些功能对比及使用代码示例

    HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,

    HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。

     

    URLConnection

    HTTPClient

    Proxies and SOCKS

    Full support in Netscape browser, appletviewer, and applications (SOCKS: Version 4 only); no additional limitations from security policies.

    Full support (SOCKS: Version 4 and 5); limited in applets however by security policies; in Netscape can't pick up the settings from the browser.

    Authorization

    Full support for Basic Authorization in Netscape (can use info given by the user for normal accesses outside of the applet); no support in appletviewer or applications.

    Full support everywhere; however cannot access previously given info from Netscape, thereby possibly requesting the user to enter info (s)he has already given for a previous access. Also, you can add/implement additional authentication mechanisms yourself.

    Methods

    Only has GET and POST.

    Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.

    Headers

    Currently you can only set any request headers if you are doing a POST under Netscape; for GETs and the JDK you can't set any headers.  Under Netscape 3.0 you can read headers only if the resource was returned with a Content-length header; if no Content-length header was returned, or under previous versions of Netscape, or using the JDK no headers can be read.

    Allows any arbitrary headers to be sent and received.

    Automatic Redirection Handling

    Yes.

    Yes (as allowed by the HTTP/1.1 spec).

    Persistent Connections

    No support currently in JDK; under Netscape uses HTTP/1.0 Keep-Alive's.

    Supports HTTP/1.0 Keep-Alive's and HTTP/1.1 persistence.

    Pipelining of Requests

    No.

    Yes.

    Can handle protocols other than HTTP

    Theoretically; however only http is currently implemented.

    No.

    Can do HTTP over SSL (https)

    Under Netscape, yes. Using Appletviewer or in an application, no.

    No (not yet).

    Source code available

    No.

    Yes.

    3.案例

    URLConnection

     String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";  
        URL url;  
        HttpURLConnection uRLConnection;  
        public UrlConnectionToServer(){  
      
        }  
        //向服务器发送get请求
        public String doGet(String username,String password){  
            String getUrl = urlAddress + "?username="+username+"&password="+password;  
            try {  
                url = new URL(getUrl);  
                uRLConnection = (HttpURLConnection)url.openConnection();  
                InputStream is = uRLConnection.getInputStream();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                uRLConnection.disconnect();  
                return response;  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
                return null;  
            } catch (IOException e) {  
                e.printStackTrace();  
                return null;  
            }  
        }  
          
        //向服务器发送post请求
        public String doPost(String username,String password){  
            try {  
                url = new URL(urlAddress);  
                uRLConnection = (HttpURLConnection)url.openConnection();  
                uRLConnection.setDoInput(true);  
                uRLConnection.setDoOutput(true);  
                uRLConnection.setRequestMethod("POST");  
                uRLConnection.setUseCaches(false);  
                uRLConnection.setInstanceFollowRedirects(false);  
                uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
                uRLConnection.connect();  
                  
                DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());  
                String content = "username="+username+"&password="+password;  
                out.writeBytes(content);  
                out.flush();  
                out.close();  
                  
                InputStream is = uRLConnection.getInputStream();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                uRLConnection.disconnect();  
                return response;  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
                return null;  
            } catch (IOException e) {  
                e.printStackTrace();  
                return null;  
            }  
        }  

    HTTPClient

    String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";  
    public HttpClientServer(){  
              
     }  
          
    public String doGet(String username,String password){  
        String getUrl = urlAddress + "?username="+username+"&password="+password;  
        HttpGet httpGet = new HttpGet(getUrl);  
        HttpParams hp = httpGet.getParams();  
        hp.getParameter("true");  
        //hp.  
        //httpGet.setp  
        HttpClient hc = new DefaultHttpClient();  
        try {  
            HttpResponse ht = hc.execute(httpGet);  
            if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
                HttpEntity he = ht.getEntity();  
                InputStream is = he.getContent();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                  
                //String str = EntityUtils.toString(he);  
                System.out.println("========="+response);  
                return response;  
            }else{  
                return "error";  
            }  
        } catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        }      
    }  
      
    public String doPost(String username,String password){  
        //String getUrl = urlAddress + "?username="+username+"&password="+password;  
        HttpPost httpPost = new HttpPost(urlAddress);  
        List params = new ArrayList();  
        NameValuePair pair1 = new BasicNameValuePair("username", username);  
        NameValuePair pair2 = new BasicNameValuePair("password", password);  
        params.add(pair1);  
        params.add(pair2);  
          
        HttpEntity he;  
        try {  
            he = new UrlEncodedFormEntity(params, "gbk");  
            httpPost.setEntity(he);  
              
        } catch (UnsupportedEncodingException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }   
          
        HttpClient hc = new DefaultHttpClient();  
        try {  
            HttpResponse ht = hc.execute(httpPost);  
            //连接成功  
            if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
                HttpEntity het = ht.getEntity();  
                InputStream is = het.getContent();  
                BufferedReader br = new BufferedReader(new InputStreamReader(is));  
                String response = "";  
                String readLine = null;  
                while((readLine =br.readLine()) != null){  
                    //response = br.readLine();  
                    response = response + readLine;  
                }  
                is.close();  
                br.close();  
                  
                //String str = EntityUtils.toString(he);  
                System.out.println("=========&&"+response);  
                return response;  
            }else{  
                return "error";  
            }  
        } catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return "exception";  
        }     
    }  

    servlet端json转化: 

    resp.setContentType("text/json");  
            resp.setCharacterEncoding("UTF-8");  
            toDo = new ToDo();  
            List<UserBean> list = new ArrayList<UserBean>();  
            list = toDo.queryUsers(mySession);  
            String body;  
    
            //设定JSON  
            JSONArray array = new JSONArray();  
            for(UserBean bean : list)  
            {  
                JSONObject obj = new JSONObject();  
                try  
                {  
                     obj.put("username", bean.getUserName());  
                     obj.put("password", bean.getPassWord());  
                 }catch(Exception e){}  
                 array.add(obj);  
            }  
            pw.write(array.toString());  
            System.out.println(array.toString());  

    android端接收:

    String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do";  
            String body =   
                getContent(urlAddress);  
            JSONArray array = new JSONArray(body);            
            for(int i=0;i<array.length();i++)  
            {  
                obj = array.getJSONObject(i);  
                sb.append("用户名:").append(obj.getString("username")).append("	");  
                sb.append("密码:").append(obj.getString("password")).append("
    ");  
                  
                HashMap<String, Object> map = new HashMap<String, Object>();  
                try {  
                    userName = obj.getString("username");  
                    passWord = obj.getString("password");  
                } catch (JSONException e) {  
                    e.printStackTrace();  
                }  
                map.put("username", userName);  
                map.put("password", passWord);  
                listItem.add(map);  
                  
            }  
              
            } catch (Exception e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
              
            if(sb!=null)  
            {  
                showResult.setText("用户名和密码信息:");  
                showResult.setTextSize(20);  
            } else  
                extracted();  
       
           //设置adapter   
            SimpleAdapter simple = new SimpleAdapter(this,listItem,  
                    android.R.layout.simple_list_item_2,  
                    new String[]{"username","password"},  
                    new int[]{android.R.id.text1,android.R.id.text2});  
            listResult.setAdapter(simple);  
              
            listResult.setOnItemClickListener(new OnItemClickListener() {  
                @Override  
                public void onItemClick(AdapterView<?> parent, View view,  
                        int position, long id) {  
                    int positionId = (int) (id+1);  
                    Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();  
                  
                }  
            });  
        }  
        private void extracted() {  
            showResult.setText("没有有效的数据!");  
        }  
        //和服务器连接  
        private String getContent(String url)throws Exception{  
            StringBuilder sb = new StringBuilder();  
            HttpClient client =new DefaultHttpClient();  
            HttpParams httpParams =client.getParams();  
              
            HttpConnectionParams.setConnectionTimeout(httpParams, 3000);  
            HttpConnectionParams.setSoTimeout(httpParams, 5000);  
            HttpResponse response = client.execute(new HttpGet(url));  
            HttpEntity entity =response.getEntity();  
              
            if(entity !=null){  
                BufferedReader reader = new BufferedReader(new InputStreamReader  
                        (entity.getContent(),"UTF-8"),8192);  
                String line =null;  
                while ((line= reader.readLine())!=null){  
                    sb.append(line +"
    ");  
                }  
                reader.close();  
            }  
            return sb.toString();  
        }  

     

  • 相关阅读:
    js异步加载服务端数据
    日期操作
    《jQuery实战》第2章 创建元素和包装集
    访问共享目录电脑盘符
    《jQuery实战》第4章 事件
    《jQuery实战》第3章 用JQuery让页面生动起来
    div + CSS 学习笔记
    WinJS Promise设置超时,可用于设置网络请求超时
    WinJS Base64编码和解码 metro
    Javascript Base64编码和解码
  • 原文地址:https://www.cnblogs.com/linxiaojiang/p/3431956.html
Copyright © 2011-2022 走看看