在项目上线前期。第三方接口的生产地址改用为 ip地址加端口号的形式(测试环境使用的是域名进行访问),导致项目上线后接口不能访问。
报错:doesn't match any of the subject alternative names: [...]
方法1:通过java代码实现忽略证书
我之前用的是httpclient发送post请求,代码如下:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zeekrlife.udepsvctasks.entity.push.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.conn.ssl.TrustSelfSignedStrategy;
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.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@Slf4j
public class HttpClientUtil {
public static JSONObject doPost(String url, String data) {
//创建post请求对象
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = new JSONObject();
//创建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(data, Charset.forName("utf-8")));
//使用CloseableHttpClient发送请求
CloseableHttpResponse response = client.execute(httpPost);
//获取返回code
int statusCode = response.getStatusLine().getStatusCode();
//根据返回code进行处理
if (statusCode == 200) {
log.info("请求:" + statusCode);
//获取响应结果
HttpEntity entity = response.getEntity();
jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
} else {
HttpEntity entity = response.getEntity();
jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
Result result = JSON.toJavaObject(jsonObject, Result.class);
log.info("请求" + statusCode);
log.info("message" + result.getMessage());
return null;
}
} catch (IOException e) {
log.info("请求失败");
log.info(e.getLocalizedMessage());
e.printStackTrace();
}
return jsonObject;
}
}
总结:当然应该还有很多其他的办法,我也在探索中。
因篇幅问题不能全部显示,请点此查看更多更全内容