4

我有一个 Java 应用程序:

-此应用程序发送一个字符串:

HttpClient httpClient = new DefaultHttpClient();

    try {
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity(xml);
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        // handle response here...
        String res= response.toString();
        System.out.println("RESPONSE=>\n"+response); //where i read the response
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

我在我的 servlet 中使用这个字符串,我只想发送一个字符串响应。

response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.print("TEST");

但是当我阅读回复时,我只有我的标题:

RESPONSE=>
HTTP/1.1 200 OK [X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7), Server: GlassFish Server Open Source Edition 3.1.2.2, Content-Type: text/html;charset=UTF-8, Content-Length: 83, Date: Fri, 14 Dec 2012 17:17:07 GMT]

有人可以帮助我吗?

4

1 回答 1

3

您使用错误的方法来阅读您的回复日期。来电:

String res= response.toString();

只是为您提供 Response 对象的字符串表示形式,而不是它包含的数据。Apache Http Commons 库有一个实用程序类,可以轻松读取响应,称为EntityUtils. 改用它来读取整个响应正文。不要忘记在执行此操作之前您需要验证请求是否实际成功完成:

if(response.getStatusLine().getStatusCode() == 200) {
    final String res = EntityUtils.toString(response.getEntity());
}
于 2012-12-14T17:38:40.863 回答