java怎么调用https外部接口
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java怎么调用https外部接口相关的知识,希望对你有一定的参考价值。
参考技术A 方法:只要New一个Map,然后把要传递的参数以键值对的形式存入Map即可。privatevoidExample()Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);java实战晋级技巧无证书访问https外部接口
楼主公司需要调用gis服务器,但是服务器提供的https请求,同时公司也没有证书,这样会照成访问后不能直接调到接口,需要手动添加证书。所以用一下方式调用https接口可以避免上述情况。
java直接访问https请求,直接复制粘贴即可。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public static void main(String[] args) throws Exception {
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
URL serverUrl = new URL("地址");
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslsession) {
//核心在这里,表示通过安全认证
return true;
}
};
//拼接请求
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection) serverUrl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
//必须设置false,否则会自动redirect到重定向后的地址
conn.setInstanceFollowRedirects(false);
conn.connect();
String result = getReturn(conn);
System.out.println(result);
}
//请求url获取返回的内容
public static String getReturn(HttpsURLConnection connection) throws IOException {
StringBuffer buffer = new StringBuffer();
try (InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
String result = buffer.toString();
return result;
}
}
}
以上是关于java怎么调用https外部接口的主要内容,如果未能解决你的问题,请参考以下文章
各位java大神,小弟跪求一个解决的方案:调用外部接口得到返回值--耗时问题