public static String dopost(String reqUrl, String json, Map<String, String> headerMap) {
String strResult = "";
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
if (reqUrl.startsWith("https")) {
//可选
httpClient = createSSLClientDefault();
} else {
httpClient = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom()
.setSocketTimeout(1 * 60 * 1000)
.setConnectTimeout(1000)
.setConnectionRequestTimeout(1000)
.build()
).build();
}
HttpEntity httpEntity = null;
try {
HttpPost httpPost = new HttpPost(reqUrl);
if (headerMap != null) {
headerMap.forEach((k, v) -> httpPost.addHeader(k, v));
}
StringEntity entity = new StringEntity(json, "UTF-8");//解决中文乱码问题
entity.setContentType("application/json");
httpPost.setEntity(entity);
response = httpClient.execute(httpPost, HttpClientContext.create());
int status = response.getStatusLine().getStatusCode();
httpEntity = response.getEntity();
if (status == 200) {
String string = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
} else {
log.error(reqUrl + " 请求错误:\r\t" + EntityUtils.toString(httpEntity, StandardCharsets.UTF_8));
}
return strResult;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return strResult;
}
public static ResultVo sendHttpsRequest(String url, String requestMethod, String
param, Map<String, String> headers, String cookieStr) {
ResultVo vo = new ResultVo();
StringBuilder result = new StringBuilder();
try {
//屏蔽证书验证
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}, new SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
// GET/POST
conn.setRequestMethod(requestMethod);
// conn.setDoOutput(true);
conn.setDoInput(true);
if ("POST".equals(requestMethod)) {
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.writeBytes(param);
wr.flush();
}
conn.setRequestProperty("Content-Type", "application/json");
} else {
if (null != param) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(param.getBytes("UTF-8"));
outputStream.close();
}
}
if (ObjectUtil.isNotEmpty(headers)) {
for (String s : headers.keySet()) {
conn.setRequestProperty(s, headers.get(s));
}
}
conn.setRequestProperty("Cookie", cookieStr);
// 设置证书忽略相关操作
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
//输出响应信息
while ((ret = br.readLine()) != null) {
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes("utf-8"), "utf-8"));
}
}
List<String> cookies = conn.getHeaderFields().get("Set-Cookie");
//这里返回了连接的cookie信息
if (cookies != null) {
for (String cookie : cookies) {
if (cookie.contains(SyncInfoConfig.COOKIE_NAME)) {
// 找到目标Cookie
String sidCookie = cookie.split(";\\s*")[0];
vo.setCookieInfo(sidCookie);
break;
}
}
}
conn.disconnect();
br.close();
}
} catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException e) {
e.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
if (ObjectUtil.isNotEmpty(result)) {
vo.setResultStr(result.toString());
}
return vo;
}
/**
* 创建默认证书
*
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
Https请求(Java)
最新推荐文章于 2024-09-04 13:09:24 发布