Https双向认证客户端请求方式

public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { 
JSONObject jsonObject = null; 
StringBuffer buffer = new StringBuffer(); 
try { 
// 创建SSLContext对象,并使用我们指定的信任管理器初始化 

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
trustKeyStore.load(trustFileInputStream, trustPasswd.toCharArray());
        tmf.init(trustKeyStore);

        trustFileInputStream.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(keyFileInputStream, keyPasswd.toCharArray());
kmf.init(ks, kp);

        SecureRandom rand = new SecureRandom();
SSLContext sslContext = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);

// 从上述SSLContext对象中得到SSLSocketFactory对象 
SSLSocketFactory ssf = sslContext.getSocketFactory(); 

URL url = new URL(requestUrl); 
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); 
httpUrlConn.setSSLSocketFactory(ssf); 

httpUrlConn.setDoOutput(true); 
httpUrlConn.setDoInput(true); 
httpUrlConn.setUseCaches(false); 
// 设置请求方式(GET/POST) 
httpUrlConn.setRequestMethod(requestMethod); 

if ("GET".equalsIgnoreCase(requestMethod)) 
httpUrlConn.connect(); 

// 当有数据需要提交时 
if (null != outputStr) { 
OutputStream outputStream = httpUrlConn.getOutputStream(); 
// 注意编码格式,防止中文乱码 
outputStream.write(outputStr.getBytes("UTF-8")); 
outputStream.close(); 
} 

// 将返回的输入流转换成字符串 
InputStream inputStream = httpUrlConn.getInputStream(); 
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 

String str = null; 
while ((str = bufferedReader.readLine()) != null) { 
buffer.append(str); 
} 
bufferedReader.close(); 
inputStreamReader.close(); 
// 释放资源 
inputStream.close(); 
inputStream = null; 
httpUrlConn.disconnect(); 
System.out.println("返回的数据:"+buffer.toString());
// jsonObject = JSONObject.fromObject(buffer.toString()); 
} catch (ConnectException ce) { 
log.error("Weixin server connection timed out."); 
} catch (Exception e) { 
log.error("https request error:{}", e); 
} 
return buffer.toString(); 
}
阅读更多
文章标签: https
上一篇解决struts2过滤器冲突的简单方法
下一篇https通讯暨SSL学习笔记思路记录
想对作者说点什么? 我来说一句

java客户端调用https资源

2014年11月17日 5KB 下载

没有更多推荐了,返回首页

关闭
关闭