有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Apache HttpClient POST不适用于实体

我开发了一个简单的基于Javasocket的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但没有成功

也许问题出在我的Web服务器上。成功请求的响应应该是什么样子? 我用这个信息:

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

共 (0) 个答案