2011年1月4日 星期二

Java Http post with SSLSocket

使用 SSL 的 程式碼如下



import java.net.*;
import java.security.Security;
import java.io.*;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


try {
String xmldata = "xx";

//Create socket
String hostname = "xxx.appspot.com";
int port = 443;
InetAddress addr = InetAddress.getByName(hostname);

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sock = (SSLSocket) factory.createSocket(hostname, port);




//Send header
String path = "/test";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Host: deltapowermeter.appspot.com\r\n");
wr.write("Connection: close\r\n");
wr.write("Content-Type: application/xml\r\n");
wr.write("Content-Length: " + xmldata.length() + "\r\n");
wr.write("\r\n");
//Send data
wr.write(xmldata);
wr.flush();

// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null)
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}

沒有留言: