使用Https发送请求
2016-12-30 15:45
253 查看
重写X509TrustManager
private static TrustManager myX509TrustManager = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } };
static public String SendHttpsPOST(String url, List<NameValuePair> param, String data)
{
String result = null;
//使用此工具可以将键值对编码成"Key=Value&Key2=Value2&Key3=Value3”形式的请求参数
String requestParam = URLEncodedUtils.format(param, "UTF-8");
try {
//设置SSLContext
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
//打开连接
//要发送的POST请求url?Key=Value&Key2=Value2&Key3=Value3的形式
URL requestUrl = new URL(url + "?" + requestParam);
HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
//设置套接工厂
httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
//加入数据
httpsConn.setRequestMethod("POST");
httpsConn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(
httpsConn.getOutputStream());
if (data != null)
out.writeBytes(data);
out.flush();
out.close();
//获取输入流
BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
int code = httpsConn.getResponseCode();
if (HttpsURLConnection.HTTP_OK == code){
String temp = in.readLine();
/*连接成一个字符串*/
while (temp != null) {
if (result != null)
result += temp;
else
result = temp;
temp = in.readLine();
}
}
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
相关文章推荐
- 使用HttpClient向HTTPS地址发送POST请求4.1.2
- 使用HttpsURLConnection发送POST请求
- 使用Apache提供的HttpClient发送https请求
- 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL
- 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL
- 使用JDK自带HttpsURLConnection发送HTTPS请求
- C++使用curl库发送https请求中文乱码问题
- 使用java发送https的请求
- 使用afnetworking和网络服务接口及soap发送并接收http/https请求:
- httpclient4.x 使用连接池发送https请求使用总结
- c#使用Socket发送HTTP/HTTPS请求的实现代码
- 使用HttpsURLConnection发送POST请求
- Web Server 使用WebClient 发送https请求 The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
- (转) httpclient4.x 使用连接池发送https请求使用总结
- PHP中使用cURL发送http/https请求
- c++使用curl库发送https请求
- Android开发中,使用https发送安全请求的实现
- 使用HttpsURLConnection发送POST请求
- 使用spring-web中的api发送http或https请求的代码