实现X509证书信任管理器类(避免导证书)
package com.showlin.httpsDemo;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
HttpRequest 和 测试
package com.showlin.httpsDemo;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpRequest {
public static String allcookie;
public static String firstCookie;
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
if (url.startsWith("https")) {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
conn.setSSLSocketFactory(ssf);
result = handleSend(conn, out, in, param);
} else {
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
result = handleSend(conn, out, in, param);
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
private static String handleSend(URLConnection conn, PrintWriter out, BufferedReader in, String param) throws IOException {
String result = "";
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("content-Type", "application/json");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
Map<String, List<String>> map=conn.getHeaderFields();
Set<String> set=map.keySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
if (key!=null&&key.equals("Set-Cookie")) {
System.out.println("key=" + key+",开始获取cookie");
List<String> list = map.get(key);
StringBuilder builder = new StringBuilder();
for (String str : list) {
builder.append(str).toString();
}
firstCookie=builder.toString();
allcookie+=firstCookie+";";
System.out.println("第一次得到的cookie="+firstCookie);
}
}
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
public static void main(String[] args) throws Exception {
String url = "https://ip:20001/apiv1/authority/login";
String message = "{\"lang\":\"zh-CN\",\"tz\":\"+8:00\",\"platform\":\"web\",\"agent\":\"ZK\",\"intfVer\":\"1.0.0\",\"sys\":\"magic-cube\",\"sessionId\":null,\"payload\":{\"params\":{\"username\":\"Admin\",\"password\":\"21232f297a57a5a\"}}}";
System.out.println(HttpRequest.sendPost(url, message));
}
}
|