java实现HTTPS接口调用

话不多说,直接上代码!

/**
	 * 安全证书管理
	 */
	class MyX509TrustManager implements 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];
		}
	}

	/**
	 * IP 域名校验
	 */
	class NullHostNameVerifier implements HostnameVerifier{
		@Override
		public boolean verify(String s, SSLSession sslSession) {
			return false;
		}
	}

	public String httpsRequest(String url,String method,String data) throws Exception{
		String resp = null;
		BufferedReader reader = null;
		InputStream in = null;
		HttpsURLConnection https = null;
		InputStreamReader inReader = null;
		StringBuffer buffer = new StringBuffer();
		try {
			//设置可以通过IP地址访问HTTPS请求
			HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
			//创建SSLContext对象,并使我们指定的信任管理器初始化
			TrustManager[] tm = {new MyX509TrustManager()};
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null,tm,new java.security.SecureRandom());
			//从上述SSLContxt对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL requestUrl = new URL(url);
			https = (HttpsURLConnection) requestUrl.openConnection();
			https.setInstanceFollowRedirects(false);
			https.setSSLSocketFactory(ssf);
			https.setDoInput(true);
			https.setDoOutput(true);
			https.setUseCaches(false);
			//设置请求方式
			https.setRequestMethod(method);
			https.connect();
			if(null != data){
				OutputStream out = https.getOutputStream();
				out.write(data.getBytes(StandardCharsets.UTF_8));
				out.close();
			}
			//将返回的输入流转换成字符串
			in = https.getInputStream();
			inReader = new InputStreamReader(in,StandardCharsets.UTF_8);
			reader = new BufferedReader(inReader);
			String str = null;
			while((str = reader.readLine()) != null){
				buffer.append(str);
			}
			resp = buffer.toString();
		}finally {
			//释放资源
			if(null != in){
				in.close();
				in = null;
			}
			if(null != reader){
				reader.close();
			}
			if(null != inReader){
				inReader.close();
			}
			if(null != https){
				https.disconnect();
			}
		}
		return resp;
	}

你可能感兴趣的:(java,https)