HttpClient4.1 使用示例

jopen 10年前發布 | 88K 次閱讀 網絡工具包 HttpClient

一、HttpClient簡介

HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,并且它支持 HTTP 協議最新的版本和建議。HttpClient 已經應用在很多的項目中,比如 Apache Jakarta 上很著名的另外兩個開源項目 Cactus 和 HTMLUnit 都使用了 HttpClient。現在HttpClient最新版本為 HttpClient 4.3.

 

二、HttpClient特性

  1. 基于標準,純凈的java語言.實現了Http1.0和Http1.1
  2. 以可擴展的面向對象的結構實現了Http全部的方法 (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE).
  3. 支持HTTPS協議.
  4. 通過Http代理建立透明的連接.
  5. 利用CONNECT 方法通過Http代理建立隧道的https連接.
  6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos 認證方案.
  7. 插件式的自定義認證方案.
  8. 便攜可靠的套接字工廠使它更容易的使用第三方解決方案.
  9. 連接管理器支持多線程應用.支持設置最大連接數,同時支持設置每個主機的最大連接數.發現并關閉過期的連接.
  10. Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
  11. 插件式的自定義Cookie策略.
  12. Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
  13. Response input streams to efficiently read the response body by streaming directly from the socket to the server.
  14. 在http1.0和http1.1中利用KeepAlive保持持久連接.
  15. 直接獲取服務器發送的response code和 headers.
  16. 設置連接超時的能力.
  17. 實驗性的支持http1.1 response caching.
  18. 源代碼基于Apache License 可免費獲取.
  19. </ol>

     

    下載地址: http://hc.apache.org/downloads.cgi

     

    三、詳細講解

    這里為了更好的理解,新建了一個java se的工程,如下圖所示

    HttpClient4.1 使用示例

     

     

    HttpClientTest類

    package com.yulore.httpproxy;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.KeyManagementException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateException;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.junit.Test;

    public class HttpClientTest {

    @Test  
    public void jUnitTest(){  
        get();  
    }  
    
    /** 
     * HttpClient連接SSL 
     */  
    private void ssl() {  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore  
                    .getDefaultType());  
            FileInputStream instream = new FileInputStream(new File(  
                    "d:\\tomcat.keystore"));  
            try {  
                // 加載keyStore d:\\tomcat.keystore  
                trustStore.load(instream, "123456".toCharArray());  
            } catch (CertificateException e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    instream.close();  
                } catch (Exception ignore) {  
                }  
            }  
            // 穿件Socket工廠,將trustStore注入  
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);  
            // 創建Scheme  
            Scheme sch = new Scheme("https", 8443, socketFactory);  
            // 注冊Scheme  
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);  
            // 創建http請求(get方式)  
            HttpGet httpget = new HttpGet(  
                    "https://localhost:8443/myDemo/Ajax/serivceJ.action");  
            System.out.println("executing request" + httpget.getRequestLine());  
            HttpResponse response = httpclient.execute(httpget);  
            HttpEntity entity = response.getEntity();  
            System.out.println("----------------------------------------");  
            System.out.println(response.getStatusLine());  
            if (entity != null) {  
                System.out.println("Response content length: "  
                        + entity.getContentLength());  
                String ss = EntityUtils.toString(entity);  
                System.out.println(ss);  
                EntityUtils.consume(entity);  
            }  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (KeyManagementException e) {  
            e.printStackTrace();  
        } catch (UnrecoverableKeyException e) {  
            e.printStackTrace();  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (KeyStoreException e) {  
            e.printStackTrace();  
        } finally {  
            httpclient.getConnectionManager().shutdown();  
        }  
    }  
    
    /** 
     * post方式提交表單(模擬用戶登錄請求) 
     */  
    private void postForm() {  
        // 創建默認的httpClient實例.  
        HttpClient httpclient = new DefaultHttpClient();  
        // 創建httppost  
        HttpPost httppost = new HttpPost(  
                "http://localhost:8080/myDemo/Ajax/serivceJ.action");  
        // 創建參數隊列  
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        formparams.add(new BasicNameValuePair("username", "admin"));  
        formparams.add(new BasicNameValuePair("password", "123456"));  
        UrlEncodedFormEntity uefEntity;  
        try {  
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            httppost.setEntity(uefEntity);  
            System.out.println("executing request " + httppost.getURI());  
            HttpResponse response;  
            response = httpclient.execute(httppost);  
            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
                System.out.println("--------------------------------------");  
                System.out.println("Response content: "  
                        + EntityUtils.toString(entity, "UTF-8"));  
                System.out.println("--------------------------------------");  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 關閉連接,釋放資源  
            httpclient.getConnectionManager().shutdown();  
        }  
    }  
    
    /** 
     * 發送 post請求訪問本地應用并根據傳遞參數不同返回不同結果 
     */  
    private void post() {  
        // 創建默認的httpClient實例.  
        HttpClient httpclient = new DefaultHttpClient();  
        // 創建httppost  
        HttpPost httppost = new HttpPost(  
                "http://localhost:8080/myDemo/Ajax/serivceJ.action");  
        // 創建參數隊列  
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        formparams.add(new BasicNameValuePair("type", "house"));  
        UrlEncodedFormEntity uefEntity;  
        try {  
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            httppost.setEntity(uefEntity);  
            System.out.println("executing request " + httppost.getURI());  
            HttpResponse response;  
            response = httpclient.execute(httppost);  
            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
                System.out.println("--------------------------------------");  
                System.out.println("Response content: "  
                        + EntityUtils.toString(entity, "UTF-8"));  
                System.out.println("--------------------------------------");  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 關閉連接,釋放資源  
            httpclient.getConnectionManager().shutdown();  
        }  
    }  
    
    /** 
     * 發送 get請求 
     */  
    private void get() {  
    
        HttpClient httpclient = new DefaultHttpClient();  
    
        try {  
            // 創建httpget.  
            HttpGet httpget = new HttpGet("http://www.baidu.com/");  
            System.out.println("executing request " + httpget.getURI());  
            // 執行get請求.  
            HttpResponse response = httpclient.execute(httpget);  
            // 獲取響應實體  
            HttpEntity entity = response.getEntity();  
            System.out.println("--------------------------------------");  
            // 打印響應狀態  
            System.out.println(response.getStatusLine());  
            if (entity != null) {  
                // 打印響應內容長度  
                System.out.println("Response content length: "  
                        + entity.getContentLength());  
                // 打印響應內容  
                System.out.println("Response content: "  
                        + EntityUtils.toString(entity));  
            }  
            System.out.println("------------------------------------");  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 關閉連接,釋放資源  
            httpclient.getConnectionManager().shutdown();  
        }  
    }  
    
    

    } </pre></div> </div>

      </div>

      詳細信息請看程序中的注釋

       

      注意事項

      JUnit運行測試時報錯,錯誤日志信息如下:

      java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
      at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:182)
      at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:150)
      at com.yulore.httpproxy.HttpClientTest.get(HttpClientTest.java:180)
      at com.yulore.httpproxy.HttpClientTest.jUnitTest(HttpClientTest.java:36)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:597)
      at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
      at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
      at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
      at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
      Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
      ... 27 more

       

      缺少commons-logging jar包,導入commons-logging.jar即可

       

      commons-logging.jar 下載地址

       本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
       轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
       本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!