JAVA调用https协议

本文提供了一个使用 Java 发起 HTTPS 请求的示例代码,详细展示了如何通过创建 SSLContext 和 SSLSocketFactory 对象来实现安全连接,同时介绍了如何绕过主机名验证及证书验证的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public static String requestIBM(String httpUrl, String httpArg) {
		    BufferedReader reader = null;
		    String result = null;
		    StringBuffer sbf = new StringBuffer();
		    httpUrl = httpUrl + "?" + httpArg;

		    try {
		    	//创建SSLContext对象,并使用我们指定的信任管理器初始化
		    	TrustManager[] tm = { new Upload()}; 
		    	SSLContext sslContext = SSLContext.getInstance("TLS"); 
		    	sslContext.init(null, tm, new java.security.SecureRandom()); 

		    	//从上述SSLContext对象中得到SSLSocketFactory对象
		    	SSLSocketFactory ssf = sslContext.getSocketFactory();
		    	URL url = new URL(httpUrl);
		    	//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
		    	HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection();
		    	httpsConn.setSSLSocketFactory(ssf);
		    	httpsConn.setRequestMethod("GET");
		        // 填入apikey到HTTP header
		    	httpsConn.setHostnameVerifier(new Upload().new TrustAnyHostnameVerifier());
		    	httpsConn.connect();
		        InputStream is = httpsConn.getInputStream();
		        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		        String strRead = null;
		        while ((strRead = reader.readLine()) != null) {
		            sbf.append(strRead);
		            sbf.append("\r\n");
		        }
		        reader.close();
		        result = sbf.toString();
		    } catch (Exception e) {
		        e.printStackTrace();
		    }
		    return result;
		}
	 public class TrustAnyHostnameVerifier implements HostnameVerifier {
	        public boolean verify(String hostname, SSLSession session) {
	            // 直接返回true
	            return true;
	        }
		}
	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1)
			throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1)
			throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值