Java使用RestfulApi-GET

Java使用RestfulApi-GET

pom.xml設定

1
2
3
4
5
6
<!-- apache http -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>

get method

get方法,傳入uri、params、headers、retry、timeout參數。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static Optional<String> get(String uri, Map<String, String> params, List<Header> headers, int retry,
int timeout) throws Exception {

for (int i = retry; i > 0; i--) {
try {
HttpGetRequest request = ApacheHttpClientManager.getInstance().getHttpGetRequest(uri);
request.setParameters(params);
request.setHeaders(headers);
request.setTimeout(timeout);
HTTPResponse httPResponse = ApacheHttpClientManager.getInstance().execute(request);
return Optional.ofNullable(httPResponse.getContent());
} catch (Exception e) {

if (1 == i) {
LogUtils.error.error(e.getMessage());
throw e;
}
continue;
}
}

return Optional.empty();
}

ApacheHttpClientManager

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public HttpGetRequest getHttpGetRequest(String url) throws Exception {
return new HttpGetRequest(url);
}

public HTTPResponse execute(HttpGetRequest request) throws Exception {
String url = request.getUrl();
if (request.getQueryString() != null) {
url = url + "?" + request.getQueryString();
}
Header[] headers = request.getHeaders();
String charset = request.getCharset();
if (charset == null) {
charset = DEFALUT_CHARSET;
}
HttpClientContext proxyHttpContext = request.getHttpContext();
RequestConfig requestConfig = request.getRequestConfig();

HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept-Charset", charset);
httpGet.setProtocolVersion(HttpVersion.HTTP_1_1);
if (requestConfig != null) {
httpGet.setConfig(requestConfig);
}
if (headers != null) {
httpGet.setHeaders(headers);
}

CloseableHttpResponse response = null;
String content = null;
CookieStore cookieStore = null;
int statusCode = 0;
Header[] responseHeaders;
try {

if (proxyHttpContext != null) {
response = httpClient.execute(httpGet, proxyHttpContext);
if (request.receiveCookie()) {
cookieStore = proxyHttpContext.getCookieStore();
}
} else {
if (request.receiveCookie()) {
HttpClientContext httpClientContext = HttpClientContext.create();
response = httpClient.execute(httpGet, httpClientContext);
cookieStore = httpClientContext.getCookieStore();
} else {
response = httpClient.execute(httpGet);
}
}
responseHeaders = response.getAllHeaders();
statusCode = response.getStatusLine().getStatusCode();

if (statusCode != 200 && statusCode != 404) {
log.info("HTTP Status-Code (" + statusCode + ") Length w/o headers: [" + url.length() + "] "
+ url);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
content = getResponse(entity);
}
} catch (HttpHostConnectException e) {
log.error(e.getMessage(), e);
httpGet.abort();
HttpHost host = e.getHost();
PoolStats pstat = cm.getTotalStats();
PoolStats pst = cm.getStats(new HttpRoute(host));
log.info(
String.format("Total PoolStats: %s & %s PoolStats: %s.", pstat, host.toHostString(), pst));
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
httpGet.abort();
throw e;
} finally {
close(response);
if (httpGet != null) {
httpGet.releaseConnection();
}
}
if (isTrace) {
log.info("HttpGet content:" + content);
}
return new HTTPResponse(statusCode, content, responseHeaders,
(cookieStore == null ? null : cookieStore.getCookies()));
}