java通过https发送post请求
/**
* 发送ssl的post请求
* https协议
* @param url 请求地址
* @param param 请求参数是 name1=value1&name2=value2 的形式。
* @return
*/
public static Object sendSSLPost(String url, String param) {
StringBuilder result = new StringBuilder();
String urlString = url + "?" + param;
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) console.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("contentType", "utf-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String ret = "";
while ((ret = bufferedReader.readLine()) != null) {
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
}
}
connection.disconnect();
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
赠人玫瑰,手有余香~
如果以上对您有帮助,请关注以下微信公众号和小程序,感谢支持!