我有一个 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]
有人可以帮助我吗?
最佳答案
您使用错误的方法来读取您的回复日期。调用:
String res= response.toString();
只是给你 Response 对象的字符串表示,而不是它包含的数据。 Apache Http Commons 库有一个实用程序类,可以轻松读取响应,称为 EntityUtils
。使用它来读取整个响应正文。不要忘记,在执行此操作之前,您需要验证请求是否确实成功完成:
if(response.getStatusLine().getStatusCode() == 200) {
final String res = EntityUtils.toString(response.getEntity());
}
关于java - 如何在 Java 客户端中读取来自 servlet 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883608/