本代码采用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());
}
}