简体   繁体   English

如何在Java中使用Socket类进行HTTP 1.1发布?

[英]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. 我正在运行带有某些虚拟主机的Tomcat服务器,并且需要从其他服务器上的另一个Servlet向该服务器上的一个Servlet发布一些数据。 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). 因为我要发布到的服务器使用虚拟主机,仅通过其IP地址引用此主机会导致问题(它不知道我要与之交谈的虚拟主机)。

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. 这是我在“ sub.example.com”上运行HTTP 1.0 POST的代码,但是在此示例中,“ example.com”仅知道将请求配置为默认子域时才将请求路由到正确的子域。 This is because of the requirement that a Socket be passed a InetAddress and not the host name. 这是因为要求向套接字传递一个InetAddress而不是主机名。

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 . 您可能会考虑通过使用Java中可用的高级HTTP客户端之一(例如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. 您仍然必须处理构造由multipart/form-encoded请求主体,但是它抽象出了构造良好multipart/form-encoded请求的许多麻烦,并使您的代码更接近真实域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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