How do I do a HTTP 1.1 Post in Java with the Socket class?
<p>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).</p>

<p>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.</p>

<pre><code>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('&amp;').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();
</code></pre>

<p>Any ideas?</p>
