Java调用Http接口和Https接口
大多数我们调用的接口都是Http的,很少有Https的接口,近期做了个项目就用到和Https接口的请求调用,和大家分享一下心得。Http接口和Https接口主要是区别还是Https存在一个证书验证。针对Https和Http做出逻辑判断,对Https接口的证书,咱们可以进行忽略。
话不多说,请看代码
Service层,http和https的接口请求
httpURLConnection = (HttpURLConnection) addUrl.openConnection();
httpURLConnection.setConnectTimeout(TIMEOUT);
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
boolean addHttps = addUrl.toString().startsWith("https");
if (addHttps) {
SSL addSSL = new SSL();
addSSL.trustAllHosts((HttpsURLConnection) httpURLConnection);
((HttpsURLConnection) httpURLConnection).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
httpURLConnection.connect();
} else {
httpURLConnection.connect();
}
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
}
工具类 SSL
public class SSL {
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
/**
* 设置不验证主机
*/
public static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
/**
* 信任所有
*
* @param connection
* @return
*/
public static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
e.printStackTrace();
}
return oldFactory;
}
}
这样,针对不同类型的http和https接口都可以请求,如有不懂可以私信我哦!!!