关闭

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

标签: https
465人阅读 评论(0) 收藏 举报
分类:
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(); 
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17355次
    • 积分:302
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:12篇
    • 译文:1篇
    • 评论:3条
    文章分类
    最新评论