java post、get请求第三方https接口
前段时间做项目新加功能由于要对接其它系统,请求系统接口传输数据。写完后发现我写的这个方法和网上现有的例子有点不太一样,可能是因为我做的项目是政务网的原因,但我想正常的即便是互联网的系统请求方式也都是一样的,所以记录一下。如果有不符合的地方请各位看官指教。废话不多说直接上代码;
注:此代码仅为测试用例仅提供思路,如果需要还需要自己完善哦。
package szsydata;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 测试用例
*/
public class ReviewProcessDemoTest {
private static final Logger logger = LoggerFactory.getLogger(ReviewProcessDemoTest.class);
/**
* 消息所属应用
*/
private static final String APP_NAME = "xxx";
/**
* 消息所属模块 须动态输入
*/
private static final String MODULE_NAME = "第三方接口要求固定的入参没有可以不要";
private static final String ENTITY_NAME = "第三方接口要求固定的入参没有可以不要";
//新增 根据文档填入ip和端口,我这里第三方接口不用加端口只用ip请求过去自动路由到真实地址
private static final String URL = "https://第三方接口ip/app-portalsp/openapi/sys-notifybus/sysNotifyComponent/send";
//列表
private static final String URL_1 = "https://第三方接口ip/app-portalsp/openapi/sys-notify/baseSysNotify/findByPerson";
private static final String URL_2 = "https://第三方接口ip/app-portalsp/openapi/sys-notifybus/sysNotifyComponent/supports";
//已查看
private static final String URL_3 = "https://第三方接口ip/app-portalsp/openapi/sys-notifybus/sysNotifyComponent/read";
//置为已办
private static final String URL_4 = "https://第三方接口ip/app-portalsp/openapi/sys-notifybus/sysNotifyComponent/done";
//恢复代办
private static final String URL_5 = "https://第三方接口ip/app-portalsp/openapi/sys-notifybus/sysNotifyComponent/resume";
//移除
private static final String URL_6 = "https://第三方接口ip/app-portalsp/openapi/sys-notifybus/sysNotifyComponent/removeTodo";
public static void main(String[] args) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("subject","请审批【测试真实地址跳转】");
params.put("notifyType","todo");
params.put("todoType","1");
params.put("link","https://fw.fgw.sz.gov.cn/lscbwzsys/#/CBJH_Apply");
params.put("appName",APP_NAME);
params.put("moduleName",MODULE_NAME);
//业务id
params.put("entityId","1e2hp5j4fw60v1fjgw3");
params.put("entityName",ENTITY_NAME);
//消息接收人,根据orgProperty指定的组织架构属性名填写接收人信息
params.put("targets", Collections.singletonList("xxxxx"));
params.put("notifyId","1e2hp5j4fw60v1fjgw3");
//固定值
params.put("orgProperty","fdLoginName");
logger.info("请求参数为:{}",params);
try {
//获取浏览器信息
CloseableHttpClient httpClient = createSSLClientDefault();
//post请求
HttpPost httpPost = new HttpPost(URL_6);
//get请求 (入参数据格式可能和示例不一致需要自己调整)
//HttpPost httpGet = new HttpGet(URL_6);
//塞入请求头信息
httpPost.setHeader("Authorization","Basic "+ Base64.getUrlEncoder().encodeToString(("szfmimp" + ":" + "P@ssw0rdtest").getBytes()));
httpPost.setHeader("accept", "*/*");
httpPost.setHeader("connection", "Keep-Alive");
httpPost.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//请求数据格式为json
StringEntity entity = new StringEntity(JSONUtil.toJsonStr(params), ContentType.create("application/json",StandardCharsets.UTF_8));
//请求数据
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity httpEntity = response.getEntity();
String responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
System.out.println(responseBody);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// https请求信任所有
@Override
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 (KeyManagementException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchAlgorithmException e) {
logger.error(e.getMessage(), e);
} catch (KeyStoreException e) {
logger.error(e.getMessage(), e);
}
return HttpClients.createDefault();
}
}
https请求三方接口另外一种写法示例集成了get和post方法使用的是Okhttp3的依赖包
package com.sydata.zt.auth.util;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections4.MapUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author :lixi
* @date :Created in 2022/9/13 9:52
* @description:
* @version:
*/
@Slf4j
public class OkHttpRequestUtils {
//private final static OkHttpClient okHttpClient = new OkHttpClient();
public static String sendGet(String url) throws Exception {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("accept", "*/*");
headerMap.put("Content-Type", "application/json; charset=UTF-8");
headerMap.put("connection", "Keep-Alive");
//设置编码语言
headerMap.put("Accept-Charset", "utf-8");
headerMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
Request.Builder builder = new Request.Builder().url(url);
if (MapUtils.isNotEmpty(headerMap)) {
headerMap.forEach(builder::addHeader);
}
Request request = builder.build();
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
.hostnameVerifier(SSLSocketClient.getHostnameVerifier())
.build();
Response response = client.newCall(request).execute();
int statusCode = response.code();
ResponseBody body = response.body();
log.info("返回状态码:{}, contentLength:{}", statusCode, body == null ? null : body.contentLength());
return resolver(body);
}
public static String sendPost(String url, String json) throws Exception {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("accept", "*/*");
headerMap.put("Content-Type", "application/json; charset=UTF-8");
headerMap.put("connection", "Keep-Alive");
//设置编码语言
headerMap.put("Accept-Charset", "utf-8");
headerMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request.Builder builder = new Request.Builder().url(url);
if (MapUtils.isNotEmpty(headerMap)) {
headerMap.forEach(builder::addHeader);
}
Request request = builder.post(requestBody).build();
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
.hostnameVerifier(SSLSocketClient.getHostnameVerifier())
.build();
Response response = client.newCall(request).execute();
int statusCode = response.code();
ResponseBody body = response.body();
log.info("返回状态码:{}, contentLength:{}", statusCode, body == null ? null : body.contentLength());
return resolver(body);
}
/**
* 解析返回值
*
* @param responseBody
* @return
*/
private static String resolver(ResponseBody responseBody) {
InputStream is = null;
String result = null;
try {
is = responseBody.byteStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String body;
StringBuilder sb = new StringBuilder();
while ((body = br.readLine()) != null) {
sb.append(body);
}
is.close();
result = sb.toString();
} catch (Exception e) {
log.error("OkHttp发送请求异常", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
log.error("Failed to close" + e.getMessage(), e);
}
}
return result;
}
}
调过证书验证的工具
package com.sydata.zt.auth.util;
import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
/**
* @author :xx
* @description:OkHttpClient跳过证书验证
* @version: 1.0
*/
public class SSLSocketClient {
/**
* 获取这个SSLSocketFactory
* */
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取TrustManager
* */
private static TrustManager[] getTrustManager() {
return new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
}
/**
* 获取HostnameVerifier
* */
public static HostnameVerifier getHostnameVerifier() {
return (s, sslSession) -> true;
}
public static X509TrustManager getX509TrustManager() {
X509TrustManager trustManager = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
trustManager = (X509TrustManager) trustManagers[0];
} catch (Exception e) {
e.printStackTrace();
}
return trustManager;
}
}
有不足之处还请指教!