天天看點

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

在工作中要用到android,然後進行網絡請求的時候,打算使用httpClient。

總結一下httpClient的一些基本使用。

版本是4.2.2。

使用這個版本的過程中,百度很多,結果都是出現的org.apache.commons.httpclient.這個包名,而不是我這裡的org.apache.http.client.HttpClient----------前者版本是Commons

HttpClient 3.x ,不是最新的版本HttpClient 4.×。

官網上面:

Commons HttpClient 3.x codeline is at the end of life. All users of Commons  HttpClient 3.x are strongly encouraged to upgrade to HttpClient 4.1. 

1.基本的get

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

public void getUrl(String url, String encoding) 

            throws ClientProtocolException, IOException { 

        // 預設的client類。 

        HttpClient client = new DefaultHttpClient(); 

        // 設定為get取連接配接的方式. 

        HttpGet get = new HttpGet(url); 

        // 得到傳回的response. 

        HttpResponse response = client.execute(get); 

        // 得到傳回的client裡面的實體對象資訊. 

        HttpEntity entity = response.getEntity(); 

        if (entity != null) { 

            System.out.println("内容編碼是:" + entity.getContentEncoding()); 

            System.out.println("内容類型是:" + entity.getContentType()); 

            // 得到傳回的主體内容. 

            InputStream instream = entity.getContent(); 

            try { 

                BufferedReader reader = new BufferedReader( 

                        new InputStreamReader(instream, encoding)); 

                System.out.println(reader.readLine()); 

            } catch (Exception e) { 

                e.printStackTrace(); 

            } finally { 

                instream.close(); 

            } 

        } 

        // 關閉連接配接. 

        client.getConnectionManager().shutdown(); 

    } 

2.基本的Post

   下面的params參數,是在表單裡面送出的參數。

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

public void postUrlWithParams(String url, Map params, String encoding) 

            throws Exception { 

        DefaultHttpClient httpclient = new DefaultHttpClient(); 

        try { 

            HttpPost httpost = new HttpPost(url); 

            // 添加參數 

            List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 

            if (params != null && params.keySet().size() >0) { 

                Iterator iterator = params.entrySet().iterator(); 

                while (iterator.hasNext()) { 

                    Map.Entry entry = (Entry) iterator.next(); 

                    nvps.add(new BasicNameValuePair((String) entry.getKey(), 

                            (String) entry.getValue())); 

                } 

            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); 

            HttpResponse response = httpclient.execute(httpost); 

            HttpEntity entity = response.getEntity(); 

            System.out.println("Login form get: " + response.getStatusLine() 

                    + entity.getContent()); 

            dump(entity, encoding); 

            System.out.println("Post logon cookies:"); 

            List<Cookie> cookies = httpclient.getCookieStore().getCookies(); 

            if (cookies.isEmpty()) { 

                System.out.println("None"); 

            } else { 

                for (int i =0; i < cookies.size(); i++) { 

                    System.out.println("- " + cookies.get(i).toString()); 

        } finally { 

            // 關閉請求 

            httpclient.getConnectionManager().shutdown(); 

3。列印頁面輸出的小代碼片段

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

private staticvoid dump(HttpEntity entity, String encoding) 

            throws IOException { 

        BufferedReader br = new BufferedReader(new InputStreamReader( 

                entity.getContent(), encoding)); 

        System.out.println(br.readLine()); 

4.常見的登入session問題,需求:使用賬戶,密碼登入系統之後,然後再通路頁面不出錯。

特别注意,下面的httpclient對象要使用一個,而不要在第二次通路的時候,重新new一個。至于如何儲存這個第一步經過了驗證的httpclient,有很多種方法實作。單例,系統全局變量(android 下面的Application),ThreadLocal變量等等。

       以及下面建立的httpClient要使用ThreadSafeClientConnManager對象!

   public String getSessionId(String url, Map params, String encoding,

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

        String url2) throws Exception { 

    DefaultHttpClient httpclient = new DefaultHttpClient( 

            new ThreadSafeClientConnManager()); 

    try { 

        HttpPost httpost = new HttpPost(url); 

        // 添加參數 

        List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 

        if (params != null && params.keySet().size() >0) { 

            Iterator iterator = params.entrySet().iterator(); 

            while (iterator.hasNext()) { 

                Map.Entry entry = (Entry) iterator.next(); 

                nvps.add(new BasicNameValuePair((String) entry.getKey(), 

                        (String) entry.getValue())); 

        // 設定請求的編碼格式 

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); 

        // 登入一遍 

        httpclient.execute(httpost); 

        // 然後再第二次請求普通的url即可。 

        httpost = new HttpPost(url2); 

        BasicResponseHandler responseHandler = new BasicResponseHandler(); 

        System.out.println(httpclient.execute(httpost, responseHandler)); 

    } finally { 

        // 關閉請求 

        httpclient.getConnectionManager().shutdown(); 

    return ""; 

5.下載下傳檔案,例如mp3等等。

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

//第一個參數,網絡連接配接;第二個參數,儲存到本地檔案的位址 

public void getFile(String url, String fileName) { 

        HttpClient httpClient = new DefaultHttpClient(); 

            ResponseHandler<byte[]> handler =new ResponseHandler<byte[]>() { 

                public byte[] handleResponse(HttpResponse response) 

                        throws ClientProtocolException, IOException { 

                    HttpEntity entity = response.getEntity(); 

                    if (entity !=

null) { 

                        return EntityUtils.toByteArray(entity); 

                    } else { 

                        return

null; 

                    } 

            }; 

            byte[] charts = httpClient.execute(get, handler); 

            FileOutputStream out = new FileOutputStream(fileName); 

            out.write(charts); 

            out.close(); 

        } catch (Exception e) { 

            e.printStackTrace(); 

            httpClient.getConnectionManager().shutdown(); 

6.建立一個多線程環境下面可用的httpClient

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

              HttpParams params = new BasicHttpParams(); 

//設定允許連結的做多連結數目 

ConnManagerParams.setMaxTotalConnections(params, 200); 

//設定逾時時間. 

ConnManagerParams.setTimeout(params, 10000); 

//設定每個路由的最多連結數量是20 

ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20); 

//設定到指定主機的路由的最多數量是50 

HttpHost localhost = new HttpHost("127.0.0.1",80); 

connPerRoute.setMaxForRoute(new HttpRoute(localhost),50); 

ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); 

//設定連結使用的版本 

HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 

//設定連結使用的内容的編碼 

HttpProtocolParams.setContentCharset(params, 

        HTTP.DEFAULT_CONTENT_CHARSET); 

//是否希望可以繼續使用. 

HttpProtocolParams.setUseExpectContinue(params, true); 

SchemeRegistry schemeRegistry = new SchemeRegistry(); 

schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80)); 

schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443)); 

ClientConnectionManager cm = new ThreadSafeClientConnManager(params,schemeRegistry); 

httpClient = new DefaultHttpClient(cm, params);  

7.實用的一個對象,http上下文,可以從這個對象裡面取到一次請求相關的資訊,例如request,response,代理主機等。

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

public staticvoid getUrl(String url, String encoding) 

        HttpContext localContext = new BasicHttpContext(); 

        // 得到傳回的response.第二個參數,是上下文,很好的一個參數! 

        httpclient.execute(get, localContext); 

        // 從上下文中得到HttpConnection對象 

        HttpConnection con = (HttpConnection) localContext 

                .getAttribute(ExecutionContext.HTTP_CONNECTION); 

        System.out.println("socket逾時時間:" + con.getSocketTimeout()); 

        // 從上下文中得到HttpHost對象 

        HttpHost target = (HttpHost) localContext 

                .getAttribute(ExecutionContext.HTTP_TARGET_HOST); 

        System.out.println("最終請求的目标:" + target.getHostName() +":" 

                + target.getPort()); 

        // 從上下文中得到代理相關資訊. 

        HttpHost proxy = (HttpHost) localContext 

                .getAttribute(ExecutionContext.HTTP_PROXY_HOST); 

        if (proxy != null) 

            System.out.println("代理主機的目标:" + proxy.getHostName() +":" 

                    + proxy.getPort()); 

        System.out.println("是否發送完畢:" 

                + localContext.getAttribute(ExecutionContext.HTTP_REQ_SENT)); 

        // 從上下文中得到HttpRequest對象 

        HttpRequest request = (HttpRequest) localContext 

                .getAttribute(ExecutionContext.HTTP_REQUEST); 

        System.out.println("請求的版本:" + request.getProtocolVersion()); 

        Header[] headers = request.getAllHeaders(); 

        System.out.println("請求的頭資訊: "); 

        for (Header h : headers) { 

            System.out.println(h.getName() + "--" + h.getValue()); 

        System.out.println("請求的連結:" + request.getRequestLine().getUri()); 

        // 從上下文中得到HttpResponse對象 

        HttpResponse response = (HttpResponse) localContext 

                .getAttribute(ExecutionContext.HTTP_RESPONSE); 

            System.out.println("傳回結果内容編碼是:" + entity.getContentEncoding()); 

            System.out.println("傳回結果内容類型是:" + entity.getContentType()); 

輸出結果大緻如下:

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

socket逾時時間:0 

最終請求的目标:money.finance.sina.com.cn:-1 

是否發送完畢:true 

請求的版本:HTTP/1.1 

請求的頭資訊:  

Host--money.finance.sina.com.cn 

Connection--Keep-Alive 

User-Agent--Apache-HttpClient/4.2.2 (java1.5) 

請求的連結:/corp/go.php/vFD_BalanceSheet/stockid/600031/ctrl/part/displaytype/4.phtml 

傳回結果内容編碼是:null 

傳回結果内容類型是:Content-Type: text/html 

8.設定代理

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

             //String  hostIp代理主機ip,int port  代理端口 

tpHost proxy = new HttpHost(hostIp, port); 

// 設定代理主機. 

tpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, 

proxy); 

9.設定保持連結時間

HttpClient4.2.2的幾個常用方法,登入之後通路頁面問題,下載下傳檔案

//在服務端設定一個保持持久連接配接的特性. 

        //HTTP伺服器配置了會取消在一定時間内沒有活動的連結,以節省系統的持久性連結資源. 

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { 

            public long getKeepAliveDuration(HttpResponse response, 

                    HttpContext context) { 

                HeaderElementIterator it = new BasicHeaderElementIterator( 

                        response.headerIterator(HTTP.CONN_KEEP_ALIVE)); 

                while (it.hasNext()) { 

                    HeaderElement he = it.nextElement(); 

                    String param = he.getName(); 

                    String value = he.getValue(); 

                    if (value !=

null && param.equalsIgnoreCase("timeout")) { 

                        try { 

                            return Long.parseLong(value) *1000; 

                        } catch (Exception e) { 

                        } 

                HttpHost target = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); 

                if("www.baidu.com".equalsIgnoreCase(target.getHostName())){ 

                    return 5*1000; 

                else 

                    return 30*1000;  

            }  

        }); 

轉賬注明出處:http://renjie120.iteye.com/blog/1727933

繼續閱讀