【日常踩坑】https接口调用不校验证书

https接口调用示例

1、POST格式调用

通过POST方式调用https接口

TrustManager[] tm = {new HttpsManager()};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("POST");
httpsURLConnection.setUseCaches(false);
httpsURLConnection.setInstanceFollowRedirects(true);
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpsURLConnection.setHostnameVerifier(new HttpsManager().new TrustAnyHostnameVerifier());
httpsURLConnection.setSSLSocketFactory(ssf);
httpsURLConnection.setDoOutput(true);
httpsURLConnection.connect();
DataOutputStream out = new DataOutputStream(httpsURLConnection.getOutputStream());
out.write(data.getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream(), "UTF-8"));
String lines;
while ((lines = responseReader.readLine()) != null) {
    result.append(lines);
}
responseReader.close();
// 断开连接
httpsURLConnection.disconnect();
2、GET格式调用

通过GET方式调用https接口
相比较于POST方式调用https接口,GET方式要注意一下几点

  • httpsURLConnection.setRequestMethod(“GET”)
  • 去掉httpsURLConnection.setDoOutput(true)
  • 去掉new DataOutputStream(httpsURLConnection.getOutputStream())。否则即使将RequestMethod设置为GET后,通过new DataOutputStream()也会将RequestMethod重置为POST
TrustManager[] tm = {new HttpsManager()};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
//将POST改为GET
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setUseCaches(false);
httpsURLConnection.setInstanceFollowRedirects(true);
httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpsURLConnection.setHostnameVerifier(new HttpsManager().new TrustAnyHostnameVerifier());
httpsURLConnection.setSSLSocketFactory(ssf);
//httpsURLConnection.setDoOutput(true);
httpsURLConnection.connect();
/** 
DataOutputStream out = new DataOutputStream(httpsURLConnection.getOutputStream());
out.write(data.getBytes("UTF-8"));
out.flush();
out.close();
**/
BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream(), "UTF-8"));
String lines;
while ((lines = responseReader.readLine()) != null) {
    result.append(lines);
}
responseReader.close();
// 断开连接
httpsURLConnection.disconnect();
不校验https证书的调用方式

某些情况下服务端只能通过https进行访问,但服务端并没有正式合法证书,这时可以通过绕过证书校验的方式访问到服务端,修改点如下(以GET方式为例):

  1. 重写TrustManager
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    }   
};
  1. 初始化sslContext
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
  1. 重写HostnameVerifier
HostnameVerifier allHostsValid = new HostnameVerifier(){
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }

};
  1. HostnameVerifier属性赋值
httpsURLConnection.setHostnameVerifier(allHostsValid);

获取http接口响应的小窍门

在服务端返回非成功(200)的状态码时,也可以通过httpsURLConnection.getErrorStream()获取返回的错误信息用于问题定位

BufferedReader responseReader = null;
if (code == 200) {
    responseReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream(), "UTF-8"));
} else {
    responseReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getErrorStream(), "UTF-8"));
}
String lines;
while ((lines = responseReader.readLine()) != null) {
    result.append(lines);
}
responseReader.close();
// 断开连接
httpsURLConnection.disconnect();
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java调用HTTPS接口并忽略证书,可以通过使用自定义的信任管理器来实现。证书验证是HTTPS通信的一部分,目的是确保通信双方的身份和保障通信的安全性。然而,有时我们需要在测试环境或特殊情况下绕过证书验证。 首先,我们需要创建一个自定义的信任管理器,该管理器将忽略证书验证。以下是一个简单的示例: ```java import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.*; public class SSLUtil { public static void ignoreSSL() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); } } ``` 接下来,在实际调用HTTPS接口之前,我们需要在代码中调用`ignoreSSL()`方法: ```java public class Main { public static void main(String[] args) { try { SSLUtil.ignoreSSL(); // 在这里进行HTTPS接口调用,忽略证书验证 // ... } catch (Exception e) { e.printStackTrace(); } } } ``` 通过使用上述代码,我们可以成功忽略证书验证,并在Java调用HTTPS接口。请注意,在生产环境中,强烈建议不要忽略证书验证,以确保通信的安全性。仅在特殊情况下,例如调试或开发环境下使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值