工具类
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 证书信任管理器(用于https请求)
*
*/
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
调用示例
String url = "";
BufferedReader in = null;
StringBuilder result = new StringBuilder("");
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
conn.setSSLSocketFactory(ssf);
// 设置通用的请求属性
conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 获取URLConnection对象对应的输出流
//out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
// flush输出流的缓冲
//out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}