1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.examples;
29
30 import java.util.concurrent.TimeUnit;
31
32 import org.apache.hc.core5.http.ClassicHttpRequest;
33 import org.apache.hc.core5.http.ClassicHttpResponse;
34 import org.apache.hc.core5.http.HttpConnection;
35 import org.apache.hc.core5.http.HttpHost;
36 import org.apache.hc.core5.http.HttpRequest;
37 import org.apache.hc.core5.http.HttpResponse;
38 import org.apache.hc.core5.http.impl.Http1StreamListener;
39 import org.apache.hc.core5.http.impl.bootstrap.HttpRequester;
40 import org.apache.hc.core5.http.impl.bootstrap.RequesterBootstrap;
41 import org.apache.hc.core5.http.io.SocketConfig;
42 import org.apache.hc.core5.http.io.entity.EntityUtils;
43 import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
44 import org.apache.hc.core5.http.message.RequestLine;
45 import org.apache.hc.core5.http.message.StatusLine;
46 import org.apache.hc.core5.http.protocol.HttpCoreContext;
47 import org.apache.hc.core5.util.Timeout;
48
49
50
51
52 public class ClassicGetExecutionExample {
53
54 public static void main(final String[] args) throws Exception {
55 final HttpRequester httpRequester = RequesterBootstrap.bootstrap()
56 .setStreamListener(new Http1StreamListener() {
57
58 @Override
59 public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
60 System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
61
62 }
63
64 @Override
65 public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
66 System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
67 }
68
69 @Override
70 public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
71 if (keepAlive) {
72 System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
73 } else {
74 System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
75 }
76 }
77
78 })
79 .setSocketConfig(SocketConfig.custom()
80 .setSoTimeout(5, TimeUnit.SECONDS)
81 .build())
82 .create();
83
84 final HttpCoreContext coreContext = HttpCoreContext.create();
85 final HttpHost target = new HttpHost("httpbin.org");
86 final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
87
88 for (int i = 0; i < requestUris.length; i++) {
89 final String requestUri = requestUris[i];
90 final ClassicHttpRequest request = ClassicRequestBuilder.get()
91 .setHttpHost(target)
92 .setPath(requestUri)
93 .build();
94 try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
95 System.out.println(requestUri + "->" + response.getCode());
96 System.out.println(EntityUtils.toString(response.getEntity()));
97 System.out.println("==============");
98 }
99 }
100 }
101
102 }