http
- 使用HttpClient
public static String doPostHttp(String url, JSONObject json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
se.setContentType("application/json");
//设置请求参数
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (Exception e) {
logger.error("发起HTTP请求失败,出现异常, url:{}, json:{}", url, json.toJSONString(), e);
logger.catching(e);
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
logger.error("发起HTTP请求失败,出现异常, url:{}, json:{}", url, json.toJSONString(), e);
logger.catching(e);
}
}
}
return null;
}
https
发送https请求时,需要对证书做处理,有两种方式:
1、生成安全证书
2、跳过安全证书。
- 使用HttpClient
public static String doPostHttps(String url, JSONObject json) {
//创建post请求对象
HttpPost httpPost = new HttpPost(url);
//创建CloseableHttpClient对象(忽略证书的重点)
CloseableHttpClient client = null;
try {
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);
client = HttpClients.custom().setSSLSocketFactory(scsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
//设置请求头
httpPost.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8")));
//使用CloseableHttpClient发送请求
CloseableHttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (IOException e) {
logger.error("发起HTTPs请求失败,出现异常, url:{}, json:{}", url, json.toJSONString(), e);
logger.catching(e);
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
logger.error("发起HTTPs请求失败,出现异常, url:{}, json:{}", url, json.toJSONString(), e);
logger.catching(e);
}
}
return null;
}
网友评论