简体   繁体   中英

How do I do a HTTP 1.1 Post in Java with the Socket class?

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?

您可能要考虑使用Apache HttpClient而不是执行原始套接字通信。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM