1

我开发了一个简单的基于 Java 套接字的 Web 服务器,它可以读取来自客户端的请求。对于客户端,我使用带有以下代码的 Apache HttpClient 库:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:7777/");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null)
{
  System.out.println(EntityUtils.toString(entity));
}

当我执行代码时,服务器从客户端获取此请求:

POST / HTTP/1.1 
Content-Length: 0
Host: localhost:7777 
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

还行吧。但现在我想通过 HTTP-POST 发送一些数据,所以我扩展了我的代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:7777/");
// Extension:
StringEntity testString = new StringEntity("Hello World!", "text/plain", "UTF-8");
httppost.addHeader(testString.getContentType());
httppost.setEntity(testString);
//
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null)
{
  System.out.println(EntityUtils.toString(entity));
}

如果我现在执行代码,则不会进入服务器。如果我删除“httppost.setEntity(testString);” 一切都会像开头描述的那样工作。所以问题一定出在“httppost.setEntity(testString);”。

有谁知道为什么当我使用“setEntity”时什么都没有发送?有没有其他方法可以传输数据?我已经尝试过这个例子: http: //svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java但是没有成功。

也许问题出在我的网络服务器上。成功请求的响应应该是什么样的?我使用此消息:

HTTP/1.1 200 OK
Server: RAKETE Web server/0.1 (Java)
Content-Length: 2
Connection: close
Content-Type: text/html
4

0 回答 0