public JSONObject httpPost(String url, JSONObject jsonParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
HttpHost target = new HttpHost("qa.chetong.net/ailoss/getAiLossPageURL", 8080,
"http");
HttpHost proxy = new HttpHost("10.1.200.95", 3128, "http");
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).setProxy(proxy).build();
httpPost.setConfig(requestConfig);
try {
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(target,httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = "";
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
log.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
System.out.println(e);
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
//测试main方法
public static void main(String[] args) {
String url = "";
String json = "";
HttpClientUtil httpClient = new HttpClientUtil();
JSONObject jsonObject = httpClient.httpPost(url,json);
}