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.client5.http.examples;
29
30 import java.io.IOException;
31
32 import org.apache.hc.client5.http.ClientProtocolException;
33 import org.apache.hc.client5.http.classic.methods.HttpGet;
34 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
35 import org.apache.hc.client5.http.impl.classic.HttpClients;
36 import org.apache.hc.core5.http.ClassicHttpResponse;
37 import org.apache.hc.core5.http.HttpEntity;
38 import org.apache.hc.core5.http.HttpStatus;
39 import org.apache.hc.core5.http.ParseException;
40 import org.apache.hc.core5.http.io.HttpClientResponseHandler;
41 import org.apache.hc.core5.http.io.entity.EntityUtils;
42
43
44
45
46
47 public class ClientWithResponseHandler {
48
49 public static void main(final String[] args) throws Exception {
50 try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
51 final HttpGet httpget = new HttpGet("http://httpbin.org/get");
52
53 System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
54
55
56 final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
57
58 @Override
59 public String handleResponse(
60 final ClassicHttpResponse response) throws IOException {
61 final int status = response.getCode();
62 if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
63 final HttpEntity entity = response.getEntity();
64 try {
65 return entity != null ? EntityUtils.toString(entity) : null;
66 } catch (final ParseException ex) {
67 throw new ClientProtocolException(ex);
68 }
69 } else {
70 throw new ClientProtocolException("Unexpected response status: " + status);
71 }
72 }
73
74 };
75 final String responseBody = httpclient.execute(httpget, responseHandler);
76 System.out.println("----------------------------------------");
77 System.out.println(responseBody);
78 }
79 }
80
81 }
82