HTTP Components簡介

基於版本4.5.xhtml

簡介

組件

  • HttpClient,核心組件
  • HC Fluent,提供了流式操做接口
  • HttpMime,提供文件上傳時用到的一些工具類
  • HttpClient Cache,有待學習
  • HttpClient OSGi,有待學習

特性

  • 基於標準、純淨的Java語言。實現了Http1.0和Http1.1
  • 以可擴展的面向對象的結構實現了Http所有的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
  • 支持HTTPS(基於SSL的HTTP)協議。
  • 經過HTTP代理創建透明的鏈接。
  • 利用CONNECT方法經過HTTP代理創建隧道的HTTPS鏈接。
  • Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO, Kerberos認證方案。
  • 插件式的自定義認證方案。
  • 便攜可靠的套接字工廠使它更容易的使用第三方解決方案(Pluggable secure socket factories, making it easier to use third party solutions)。
  • 支持多線程應用的鏈接管理器。支持設置最大鏈接數,同時支持設置每一個主機的最大鏈接數,發現並關閉過時的鏈接。
  • 自動處理Set-Cookie中的Cookie。(Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.)
  • 插件式的自定義Cookie策略。
  • Request的輸出流能夠避免流中內容直接緩衝到socket服務器。(Request output streams to avoid buffering any content body by streaming directly to the socket to the server.)
  • Response的輸入流能夠有效的從socket服務器直接讀取相應內容。
  • 在http1.0和http1.1中利用KeepAlive保持持久鏈接。
  • 直接獲取服務器發送的response code和 headers。
  • 可設置鏈接超時。
  • 支持http1.1 response caching。
  • 源代碼基於Apache License 可免費獲取。

Quick Start

HTTP Client

GET請求、POST請求 及 response處理apache

CloseableHttpClient httpclient = HttpClients.createDefault();

//GET請求及response處理
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager. 
try {
    System.out.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity1);
} finally {
    response1.close();
}

//POST請求及response處理
HttpPost httpPost = new HttpPost("http://targethost/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);

try {
    System.out.println(response2.getStatusLine());
    HttpEntity entity2 = response2.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity2);
} finally {
    response2.close();
}

官網的例子註釋中有幾點是須要注意的:服務器

  • 調用httpclient.execute(XXX)後,http鏈接會一直被response持有,須要調用CloseableHttpResponse#close(),固然也但是已使用jdk1.7的try-catch-resource。
  • 若是response沒有充分的被消耗掉(好比:chunk模式下,只取了部分),會被connection manager丟棄而不能複用,使用EntityUtils.consume(entity)能夠確保response被充分消耗

HC Fluent 的流式接口

Request.Get("http://targethost/homepage")
    .execute().returnContent();
Request.Post("http://targethost/login")
    .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())
    .execute().returnContent();

HttpMime 提交文件

multipart/form 類型的POST,下面例子中的FileBody、StringBody、MultipartEntityBuilder等都是HttpMine模塊中的類。多線程

public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/fileUpload");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

參考

HTTP Client使用詳解
HttpClient Quick startapp

相關文章
相關標籤/搜索