CLOVER馃崁

That was when it all began.

Java銇с伄HttpClient銈点兂銉椼儷 銇濄伄2

銇撱仭銈夈伄銈ㄣ兂銉堛儶銇佺稓绶ㄧ殑銇倓銇ゃ仹銇欍

Java銇с伄HttpClient銈点兂銉椼儷
http://d.hatena.ne.jp/Kazuhira/20131026/1382796711

銇撱倢銈掓浉銇勩仧寰屻伀銆併亜銇忋仱銇嬫皸銇仾銈婬TTP銈儵銈ゃ偄銉炽儓銉┿偆銉栥儵銉倰瑕嬨仸銇亜銇熴伄銇с仚銇屻併仛銇c仺瑙︺倝銇亜銇俱伨銇犮仯銇熴伄銇с亾銈屻倰姗熴伀銇ㄦ濄亜銇俱仐銇︺

銇撱仭銈夈伄銈ㄣ兂銉堛儶銇佽Е鐧恒仌銈屻仧銇ㄣ亜銇嗐伄銈傘亗銈娿伨銇欍

google-http-java-client 鍏ラ杸
http://vividcode.hatenablog.com/entry/java/google-http-java-client

銇涖仯銇嬨亸銇伄銇сgoogle-http-java-client鍚倎銇﹁│銇椼仸銇勩仯銇︺伩銇俱仚銆

銇亰銆併偟銉炽儣銉仺銇椼仸銇墠鍥炲悓妲

銈点兂銉椼儷銇ㄣ仐銇︺伅銆

銇ㄣ仐銇︽浉銇勩仸銇勩亶銇俱仚銆

銇俱仧銆侀氫俊鐩告墜銇瓾TTP銈点兗銉愩倐鍚屾銇獹roovy銇ф浉銇勩仧銈傘伄銈掍娇鐢ㄣ仐銇︺亜銇俱仚銆傘亾銈屻亱銈Java銈炽兗銉夈仹瑷樿堪銇欍倠銈€偗銈汇偣鍏堛伀瀵俱仐銇︺curl銇с儶銈銈ㄣ偣銉堛倰鎶曘亽銈嬨仺銇撱亞銇勩亞绲愭灉銇仾銈娿伨銇欍

## GET
$ curl http://localhost:8080/get?param=value
Accessed URL = /get?param=value
Accessed Method = GET
Accessed Date = Sat Nov 15 20:41:08 JST 2014


## POST
$ curl -X POST http://localhost:8080/post -d '<<EOF
POST BODY
Hello Http Server!!
EOF
'
Accessed URL = /post
Accessed Method = POST
Accessed Date = Sat Nov 15 20:45:22 JST 2014
Request Body<<
<<EOF
POST BODY
Hello Http Server!!
EOF
>>

銈炽兗銉変緥銇伅銉嗐偣銉堛偝銉笺儔銈掍娇鐢ㄣ仐銇俱仚銇仹銆JUnit銇ˋssertJ銈掍娇銇勩伨銇欍

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <version>1.7.0</version>
      <scope>test</scope>
    </dependency>

鏇搞亸銉嗐偣銉堛偝銉笺儔銇с伅銆佷互涓嬨伄import鏂囥亴鍏ャ仯銇︺亜銈嬨倐銇仺銇椼伨銇欍

import static org.assertj.core.api.Assertions.*;

import org.junit.Test;

銇с伅銆併亜銇c仸銇裤伨銇欍

銇亰銆佷粖鍥炪仈绱逛粙銇欍倠HTTP銈儵銈ゃ偄銉炽儓銇併亜銇氥倢銈備綍銈夈亱銇瓾TTP閫氫俊銉┿偆銉栥儵銉伄涓娿伀妲嬬瘔銇曘倢銇熴倐銇伀銇倞銇俱仚銆

Async Http Client

浠婂洖銆1鐣│銇椼仸銇裤仧銇嬨仯銇烪TTP銈儵銈ゃ偄銉炽儓銇с仚銆備粬銇JVM瑷瑾炪仹浣裤倧銈屻仸銇勩倠HTTP銈儵銈ゃ偄銉炽儓銇唴閮ㄣ仹銈備娇銈忋倢銇熴倞銇椼仸銇勩倠銆侀潪鍚屾湡HTTP閫氫俊銈掕銇嗐儵銈ゃ儢銉┿儶銇с仚銆

Async Http Client
https://github.com/AsyncHttpClient/async-http-client
https://asynchttpclient.github.io/async-http-client/

Web銈点偆銉堛伄銉夈偔銉ャ儭銉炽儓銇佸彜銇勭偣銇屻亗銈嬨伄銇ф敞鎰忋仐銇︺亸銇犮仌銇勩

Maven渚濆瓨闁總銆

    <dependency>
      <groupId>com.ning</groupId>
      <artifactId>async-http-client</artifactId>
      <version>1.8.14</version>
    </dependency>

import鏂囥

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;

GET銇緥銆

    @Test
    public void testAsynHttpClientGet() {
        try (AsyncHttpClient client = new AsyncHttpClient()) {
            Response response =
                client
                .prepareGet("http://localhost:8080/get?param=value")
                .execute()
                .get();

            assertThat(response.getStatusCode())
                .isEqualTo(200);
            assertThat(response.getResponseBody("UTF-8"))
                .contains("Accessed URL = /get?param=value",
                          "Accessed Method = GET");
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

POST銇緥銆

    @Test
    public void testAsynHttpClientPost() {
        try (AsyncHttpClient client = new AsyncHttpClient()) {
            StringBuilder builder = new StringBuilder();
            builder.append("POST Body");
            builder.append("\r\n");
            builder.append("Hello Http Server!!");
            builder.append("\r\n");

            Response response =
                client
                .preparePost("http://localhost:8080/post")
                .setBody(builder.toString())
                .execute()
                .get();

            assertThat(response.getStatusCode())
                .isEqualTo(200);
            assertThat(response.getResponseBody("UTF-8"))
                .contains("Accessed URL = /post",
                          "Accessed Method = POST",
                          "Request Body<<",
                          "POST Body",
                          "Hello Http Server!!",
                          ">>");
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

銇勩仛銈屻倐銆乪xecute銉°偨銉冦儔銈掑懠銇冲嚭銇椼仧寰屻伀get銉°偨銉冦儔銇懠銇冲嚭銇椼亴鍏ャ仯銇︺亜銇俱仚銇屻併亾銈屻伅Future#get銇仾銈娿伨銇欍傘仾銇仹銆併亜銇c仧銈揊uture銇у彈銇戙仸寰屻仹绲愭灉銈掑彇銈婂嚭銇欍亾銇ㄣ倐鍙兘銇ㄣ亜銇嗐亾銇ㄣ伀銇倞銇俱仚銆

AsyncHttpClient銇丆loseable銇с仚銆

AsyncHandler銈ゃ兂銈裤兗銉曘偋銉笺偣銇ㄣ亜銇嗐倐銇倰浣裤仯銇︺併偝銉笺儷銉愩儍銈倰鍙椼亼銈嬨偣銈裤偆銉仹鏇搞亸銇撱仺銈傘仹銇嶃伨銇欍備互涓嬨伄銈炽兗銉夈仹銇丄syncHandler銈ゃ兂銈裤兗銉曘偋銉笺偣銇嫛寮点仹銇傘倠銆丄syncCompleteHandler銈掍娇鐢ㄣ仐銇︺亜銇俱仚銆

    @Test
    public void testAsynHttpClientGetWithHandler() {
        try (AsyncHttpClient client = new AsyncHttpClient()) {
            String responseData =
                client
                .prepareGet("http://localhost:8080/get?param=value")
                .execute(new AsyncCompletionHandler<String>() {
                        @Override
                        public String onCompleted(Response response) throws Exception {
                            return response.getResponseBody("UTF-8");
                        }
                    })
                .get();

            assertThat(responseData)
                .contains("Accessed URL = /get?param=value",
                          "Accessed Method = GET");
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

銇俱仧銆丄sync Http Client銇佷互涓嬨伄HTTP閫氫俊銉┿偆銉栥儵銉倰鍩虹洡銇ㄣ仐銇︿娇鐢ㄣ仚銈嬨亾銇ㄣ亴銇с亶銇俱仚銆

  • Netty锛堛儑銉曘偐銉儓锛
  • Grizzly
  • Commons HttpClient
  • java.net.URL

銉囥儠銈┿儷銉堛伅Netty銇с丆ommons HttpClient銇仼銇儵銈ゃ儢銉┿儶銈掍娇鐢ㄣ仚銈嬪牬鍚堛伅銆併偑銉椼偡銉с兂銇ㄣ仾銇c仸銇勩倠渚濆瓨闁總銇拷鍔犮亴蹇呰銇с仚銆

渚嬨亪銇般丆ommons HttpClient銈掍娇銇嗗牬鍚堛伅銆佷互涓嬨伄渚濆瓨闁總銇

    <!-- Async Http Client, using Commons Http Client-->
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>

import鏂囥倰杩藉姞銇椼仸

// for Async Http Client, using Apache Http Client 3.1 
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.providers.apache.ApacheAsyncHttpProvider;

銇撱伄銈堛亞銇偝銉笺儔銇仾銈娿伨銇欍

    @Test
    public void testAsynHttpClientGetUsingCommonsHttpClient() {
        AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
        AsyncHttpProvider provider = new ApacheAsyncHttpProvider(builder.build());

        try (AsyncHttpClient client = new AsyncHttpClient(provider)) {
            Response response =
                client
                .prepareGet("http://localhost:8080/get?param=value")
                .execute()
                .get();

            assertThat(response.getStatusCode())
                .isEqualTo(200);
            assertThat(response.getResponseBody("UTF-8"))
                .contains("Accessed URL = /get?param=value",
                          "Accessed Method = GET");
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

銇撱伄閮ㄥ垎銇屻佸皯銇楅暦銇忋仾銈娿伨銇椼仧銇

        AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
        AsyncHttpProvider provider = new ApacheAsyncHttpProvider(builder.build());

        try (AsyncHttpClient client = new AsyncHttpClient(provider)) {

API鐨勩伀銇併仾銇嬨仾銇嬩娇銇勩倓銇欍仢銇嗐仾HTTP銈儵銈ゃ偄銉炽儓銉┿偆銉栥儵銉仩銇ㄦ濄亜銇俱仚銆

渚濆瓨銉┿偆銉栥儵銉亴鍙ゃ亜锛圢etty銇3绯汇丆ommons HttpClient浣跨敤锛夈仾銇仹銇欍亴銆GitHub銇甿aster銇仚銇с伀銉戙儍銈便兗銈稿悕銇嬨倝澶夈倧銇c仧2绯汇亴閫层倱銇с亜銈嬨倛銇嗐仹銇欍傘仧銇犮丳rovider銇儴鍒嗐伅Netty銇℅rizzly銇椼亱銇仌銇濄亞銇с仐銇熴亴銆

銇俱亗銆侀氫俊鍩虹洡銇疦etty銇ц壇銇勩仺鎬濄亞銇仹銆2绯汇伄鐧诲牬銇仱銇勩仸銈傚緟銇c仸銇勩倛銇嗐仺鎬濄亜銇俱仚銆

銇傘仺銆乁RL銈ㄣ兂銈炽兗銉銈扐syncHttpClient銇换銇涖倠鍫村悎銇佺⒑銇UTF-8鍥哄畾銇犮仯銇熸皸銇屻仐銇熴倛銇嗐仾鈥︺

google-http-java-client

銇撱仭銈夈伅銆佸墠杩般伄銉栥儹銈般倰瑕嬨倠銇俱仹瀛樺湪銈掔煡銈夈仾銇嬨仯銇熴Google銇倛銈婬TTP銈儵銈ゃ偄銉炽儓銉┿偆銉栥儵銉仹銇欍傚弬鐓у厛銇鏄庛亴瑭炽仐銇勩伄銇с佽┏绱般伅銇濄仭銈夈伕鈥︺

google-http-java-client
https://code.google.com/p/google-http-java-client/

Apache HttpComponents銆java.net.URL銆併仢銇椼仸Google App Engine鍚戙亼銇疅瑁呫倰鍚倱銇燞TTP銈儵銈ゃ偄銉炽儓銇倛銇嗐仹銇欍

Apache HttpComponents銇佸皯銇楀彜銇忋仸4.0.1銇緷瀛樸仐銇︺亜銇俱仚锛google-http-java-client銇1.19.0鏅傜偣锛夈

Maven渚濆瓨闁總銆

    <dependency>
      <groupId>com.google.http-client</groupId>
      <artifactId>google-http-client</artifactId>
      <version>1.19.0</version>
    </dependency>

import鏂囥

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.apache.ApacheHttpTransport;

銇撱亾銇с伅銆Apache HttpComponents銈掍娇銇嗐亾銇ㄣ伀銇椼伨銇欍

GET銇緥銆

    @Test
    public void testGoogleHttpJavaClientGet() {
        HttpTransport transport = new ApacheHttpTransport();
        HttpRequestFactory factory = transport.createRequestFactory();

        GenericUrl url = new GenericUrl("http://localhost:8080/get?param=value");

        try {
            HttpRequest request = factory.buildGetRequest(url);
            HttpResponse response = request.execute();

            try {
                assertThat(response.getStatusCode())
                    .isEqualTo(200);
                assertThat(response.parseAsString())
                    .contains("Accessed URL = /get?param=value",
                              "Accessed Method = GET");
            } finally {
                response.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                transport.shutdown();
            } catch (IOException e ) {
                e.printStackTrace();
            }
        }
    }

POST銇緥銆

    @Test
    public void testGoogleHttpJavaClientPost() {
        HttpTransport transport = new ApacheHttpTransport();
        HttpRequestFactory factory = transport.createRequestFactory();

        GenericUrl url = new GenericUrl("http://localhost:8080/post");

        try {
            StringBuilder builder = new StringBuilder();
            builder.append("POST Body");
            builder.append("\r\n");
            builder.append("Hello Http Server!!");
            builder.append("\r\n");

            HttpRequest request =
                factory.buildPostRequest(url,
                                         new InputStreamContent("text/plain",
                                                                new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8))));
            HttpResponse response = request.execute();

            try {
                assertThat(response.getStatusCode())
                    .isEqualTo(200);
                assertThat(response.parseAsString())
                    .contains("Accessed URL = /post",
                              "Accessed Method = POST",
                              "Request Body<<",
                              "POST Body",
                              "Hello Http Server!!",
                              ">>");
            } finally {
                response.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                transport.shutdown();
            } catch (IOException e ) {
                e.printStackTrace();
            }
        }
    }

HttpTransport#shutdown銇併亰浣滄硶鐨勩伀鍛笺伋鍑恒仐銇熸柟銇屻倛銇曘仢銇嗐仹銇欍伃銆傜壒銇Apache HttpComponents銈掍娇銇c仧鍫村悎銇併亾銈屻伄鍛笺伋鍑恒仐銇孒ttpClient#getConnectionManager#shutdown銇仾銇c仸銇勩伨銇欍伄銇с

jcabi-http

鏈寰屻伅銆併仭銈囥仯銇ㄥ墠銇銇嬨亼銇熴倐銇仹銆乯cabi-http銇с仚銆傘亾銇°倝銈傘併仢銈屻伝銇╂儏鍫便倰瑕嬨仧銇撱仺銇仾銇勩仹銇欍亴鈥︺

Fluent HTTP Client
http://http.jcabi.com/

閫氫俊鍩虹洡銇Apache HttpComponents銇java.net.URL銇с丠TTP閫氫俊銈扚luent銇浉銇戙倠銉┿偆銉栥儵銉仹銇欍

Maven渚濆瓨闁總銆

    <dependency>
      <groupId>com.jcabi</groupId>
      <artifactId>jcabi-http</artifactId>
      <version>1.9.2</version>
    </dependency>

寮曘仯寮点倝銈屻仸銇忋倠渚濆瓨闁總銇屻佷笂瑷2銇ゃ伄銉┿偆銉栥儵銉伀姣斻伖銇﹀銈併仾銇亴銇°倗銇c仺姘椼伀銇倠銇ㄣ亾銈嶃仩銇c仧銈娿仐銇俱仚鈥︺

import鏂囥

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.jcabi.http.Request;
import com.jcabi.http.Response;
import com.jcabi.http.request.JdkRequest;

銇俱仛銇丣dkRequest锛java.net.URL锛夈倰浣裤仯銇︺伩銇俱仚銆

GET銇緥銆

    @Test
    public void testJcabiHttpGet() {
        try {
            Response response =
                new JdkRequest("http://localhost:8080/get?param=value")
                .method(Request.GET)
                .fetch();

            assertThat(response.status())
                .isEqualTo(200);
            assertThat(response.body())
                .contains("Accessed URL = /get?param=value",
                          "Accessed Method = GET");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

POST銇緥銆

    @Test
    public void testJcabiHttpPost() {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("POST Body");
            builder.append("\r\n");
            builder.append("Hello Http Server!!");
            builder.append("\r\n");

            Response response =
                new JdkRequest("http://localhost:8080/post")
                .method(Request.POST)
                .fetch(new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)));

            assertThat(response.status())
                .isEqualTo(200);
            assertThat(response.body())
                .contains("Accessed URL = /post",
                          "Accessed Method = POST",
                          "Request Body<<",
                          "POST Body",
                          "Hello Http Server!!",
                          ">>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

鐗广伀銈儹銉笺偤闁總銇懠銇冲嚭銇椼亴銇亜銇с仚銇屻丷equest#fetch銇懠銇冲嚭銇楁檪銇併偗銉兗銈哄嚘鐞嗐亴鍏ャ仯銇︺亜銈嬨倛銇嗐仹銇欍

缍氥亜銇︺侀氫俊銉┿偆銉栥儵銉倰Apache HttpComponents銇垏銈婃浛銇堛仸銇裤伨銇欍Maven渚濆瓨闁總銇互涓嬨倰杩藉姞銆

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <version>4.3.3</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.3.3</version>
    </dependency>

import鏂囥伀浠ヤ笅銈掕拷鍔犮

import com.jcabi.http.request.ApacheRequest;

GET銇緥銇犮仺銆併亾銇倛銇嗐伀銇倞銇俱仚銆

    @Test
    public void testJcabiHttpGetUsingApacheHttpComponents() {
        try {
            Response response =
                new ApacheRequest("http://localhost:8080/get?param=value")
                .method(Request.GET)
                .fetch();

            assertThat(response.status())
                .isEqualTo(200);
            assertThat(response.body())
                .contains("Accessed URL = /get?param=value",
                          "Accessed Method = GET");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

銇俱亗銆併亾銇撱亴澶夈倧銇c仧銇犮亼銇с仚銇屻

                new ApacheRequest("http://localhost:8080/get?param=value")

銇濄倢銇

绨″崢銇娇銇勬柟銈掋仏銇c仺杓夈仜銇熴仩銇戙伄銇旂垂浠嬨併仺銇勩亞鎰熴仒銇с仐銇熴亴瀹熼殯銇仼銈屻倰浣裤亞銇嬨伅API銇ソ銇裤仺銇嬨仹鑹亜銇ㄦ濄亜銇俱仚銆

鍊嬩汉鐨勩伀銇銉囥兗銈垮舰寮銇鎻涖仺銇嬨伅銇濄倢銇汇仼銇撱仩銈忋倝銇亸銇︺亜銇勩伄銇с佺啊娼斻伀鏇搞亼銈嬨倐銇仹銇傘倢銇般仢銈屻仹銇勩亜姘椼亴銇椼仸銇勩伨銇欍

Apache HttpComponents銇侀珮姗熻兘銇с伅銇傘倞銇俱仚銇屻亜銈嶃亜銈嶅啑闀枫仩銇c仧銈娿併儶銈姐兗銈归枹淇傘仹銉忋優銈嬨仾銇┿併亗銇俱倞鑹亜鍗拌薄銇屻仾銇忋仸銇с仚銇︺仺銇亜銇堛佷粫浜嬨仩銇ㄣ亾銇°倝銈掍娇銇嗐亾銇ㄣ倐澶氥亜銇仹銇欍亴鈥︺