Wednesday, July 4, 2007

Java: Send a Http Request

Here is the sample code for sending a http request using Java Library

===================================================
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;

public class HttpTest extends Thread{
public static void main(String[] args) {
try {
URL u = new URL("http://192.168.1.10:80/http/incoming");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setRequestMethod("POST");
uc.setRequestProperty("Host" , "1.1.1.1");
uc.setRequestProperty("Accept", "*/*");
uc.setRequestProperty("Content-Type", "application/octet-stream");
uc.setDoOutput(true);
uc.connect();
OutputStream os = uc.getOutputStream();
os.write("123456".getBytes());
uc.disconnect();
System.out.println("Response code: " + uc.getResponseCode());
String key = null;
for (int i=1; ((key = uc.getHeaderFieldKey(i))!=null); i++) {
System.out.println(key + ": " + uc.getHeaderField(key));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

===================================================

In my opinion, if it was a very simple application such as only sending a simple message via HTTP protocol, it was better to implement by yourself because it is more flexible and more efficient. I did it in my current project. However, there is a risk for implement by yourself. It's that Java Sock library is not thread safe. Be careful.

Here is a HTTP message sample:
==============================================
POST /http/incoming HTTP/1.1
Accept: */*
Content-Length: 6
Host: 192.168.1.10:80
Content-Type: application/octet-stream
Date: 2007-07-04 12:12:12

123456
==============================================

No comments: