tags:

views:

416

answers:

2

I'm running a Tomcat server with some virtual hosts and I need to POST some data to a servlet on this server from another servlet on another server. Because the server that I am POSTing to uses virtual hosts just referring to this host by it's IP address will cause problem (it won't know what virtual host I'm trying to talk to).

Here is the code I have for running an HTTP 1.0 POST to "sub.example.com", but in this example "example.com" only knows to route the request to the right sub domain if it is configured as the default. This is because of the requirement that a Socket be passed a InetAddress and not the host name.

String host = "sub.example.com";
int port = 80;
String path = "/Servlet";
StringBuilder data = new StringBuilder();
data.append(URLEncoder.encode("NameA", "UTF-8")).append('=').append(URLEncoder.encode("ValueA", "UTF-8"));
data.append('&').append(URLEncoder.encode("NameB", "UTF-8")).append('=').append(URLEncoder.encode("NameB", "UTF-8"));

InetAddress addr = InetAddress.getByName(host);
Socket socket = new Socket(addr, port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

wr.write("POST "+path+" HTTP/1.0\r\n");
wr.write("Content-Length: "+data.length()+"\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
// Send data
wr.write(data.toString());
wr.flush();
wr.close();

Any ideas?

+4  A: 

You might consider making life a little easier on yourself by using one of the higher-level HTTP clients available in Java, such as HttpURLConnection. You'll still have to handle constructing the multipart/form-encoded request body, but it abstracts away much of the hassle of constructing a well-formed request, and brings your code closer to the true domain.

Rob
+5  A: 

You may want to consider using Apache HttpClient rather than performing raw socket communications.

Steve Kuo
For this task, it looks like this works. However what I am also trying to do is tell the remote server to start an action that might take minutes to complete. In this case I need the immediate feedback that the command has been sent and processed but I don't care about it's output (once I know that the server received the command) which it looks like the Apache HttpClient class encapsulates.
Jason Sperske