直接上代码
构建post请求
public static String post(String url, JSONObject json, int timeOut) throws UnsupportedEncodingException {
PostMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(json.toJSONString(), "application/json", StandardCharsets.UTF_8.name()));
return request(method, timeOut);
}
发送请求
public static String request(HttpMethod method, int timeOut) {
HttpClient httpClient = new HttpClient();
HostConfiguration hc = new HostConfiguration();
// hc.setProxy(ip, port);代理
httpClient.setHostConfiguration(hc);
httpClient.getParams().setConnectionManagerTimeout(timeOut * 1000);
httpClient.getParams().setSoTimeout(timeOut * 1000); // 120s timeout
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("request status code error: " + statusCode);
}
return method.getResponseBodyAsString();
} catch (Exception e) {
throw new RuntimeException("request exception:"+e.getMessage(), e);
} finally {
method.releaseConnection();
}
}