2011年1月4日 星期二

Java Http post with Socket

程式碼如下


import java.net.*;
import java.io.*;

try {
String xmldata ="QQ";

//Create socket
String hostname = "xxx.appspot.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);


//Send header
String path = "/powermeter/event";
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());
System.out.println("ASS");
}

沒有留言: