java双向SSL的http请求(客户端)

本代码采用socket请求restful webservice,使用POST修改其中的内容。
package com.iss.restfuldemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

//双向SSL
public class Test {
static final int HTTPS_PORT = 7002;

private static final String CLIENT_KEY_STORE_PASSWORD = "123456";
private static final String CLIENT_TRUST_KEY_STORE_PASSWORD = "123456";

public static void main(String argv[]) throws Exception {
// 受访主机
String host = "10.24.195.28";
// 受访的页面
String url = "/OSB_Project/HelloworldRestProxy/0003";
// 得到上下文
SSLContext ctx = SSLContext.getInstance("SSL");

// 导入keystore和truststore
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

KeyStore ks = KeyStore.getInstance("JKS");
KeyStore tks = KeyStore.getInstance("JKS");

ks.load(new FileInputStream("kclient.jks"), CLIENT_KEY_STORE_PASSWORD
.toCharArray());
tks.load(new FileInputStream("tclient.jks"),
CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());

kmf.init(ks, CLIENT_KEY_STORE_PASSWORD.toCharArray());
tmf.init(tks);

// 初始化
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// 获得工厂
SSLSocketFactory factory = ctx.getSocketFactory();
// 从工厂获得Socket连接
Socket socket = factory.createSocket(host, HTTPS_PORT);
// 剩下的就和普通的Socket操作一样了
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String data = "<?xml version='1.0' encoding='UTF-8'?><Helloworld><ID>0003</ID><name>xiugai</name></Helloworld>";
out.write("POST " + url + " HTTP/1.0\n");
out.write("Content-Type: text/xml\n");
out.write("Content-Length: " + data.length() + "\n");
out.write("\n");
out.write(data);
out.flush();

System.out.println("start work!");
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
out.close();
in.close();
System.out.println(sb.toString());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值