HttpClient重试机制 --自定义HttpRequestRetryHandler 更新
- UID
- 1066743
|
HttpClient重试机制 --自定义HttpRequestRetryHandler 更新
public static final String doPostWithRequest(String path, HttpServletRequest request) {
Enumeration params = request.getParameterNames();
List<NameValuePair> nameValuePairs = Lists.newArrayList();
while (params.hasMoreElements()) {
String paramName = (String) params.nextElement();
nameValuePairs.add(new BasicNameValuePair(paramName, request.getParameter(paramName)));
}
HttpPost httpPost = new HttpPost(path);
httpPost.setConfig(REQUEST_CONFIG_TIME_OUT);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
return execReq(httpPost);
} catch (UnsupportedEncodingException e) {
logger.error("do post error: ", e);
}
return "";
}
public static final String doPost(String path, Map<String, Object> params) {
logger.debug("doPost from " + path, params);
HttpPost httpPost = new HttpPost(path);
httpPost.setConfig(REQUEST_CONFIG_TIME_OUT);
try {
httpPost.setEntity(new UrlEncodedFormEntity(createParams(params)));
String bodyAsString = execReq(httpPost);
if (bodyAsString != null) return bodyAsString;
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
}
return errorResponse("-2", "unknown error");
}
private static List<NameValuePair> createParams(Map<String, Object> params) {
List<NameValuePair> nameValuePairs = Lists.newArrayList();
for (Map.Entry<String, Object> entry : params.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
return nameValuePairs;
}
private static String execReq(HttpPost httpPost) {
try {
CloseableHttpResponse response = getClient(true).execute(httpPost);
if (response != null) {
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else {
return errorResponse(String.valueOf(response.getStatusLine().getStatusCode()),
"http post request error: " + httpPost.getURI());
}
} finally {
EntityUtils.consume(response.getEntity());
}
} else {
return errorResponse("-1", "response is null");
}
} catch (IOException e) {
logger.error("doPost error: ", e);
}
return errorResponse("-3", "unknown error");
}
private static String errorResponse(String code, String msg) {
return JSON.toJSONString(ImmutableMap.of("code", code, "msg", msg));
}
} |
|
|
|
|
|