【问题标题】:Java Apache HttpComponents, how to read POST response?Java Apache HttpComponents,如何读取 POST 响应?
【发布时间】:2012-12-31 03:20:25
【问题描述】:

我正在使用 Java 中的 HttpComponents 将登录信息发布到网站。登录后,我想发送更多 POST 数据,具体取决于返回的网页。我不确定如何实际打印或查看服务器因发送我的 POST 数据而返回的 html/网页(也许我正在寻找的是响应正文?)。

所有的教程似乎只展示了如何查看标头信息或服务器代码。我认为这可能是我缺少的一些简单的东西。有可能是我不太了解这个过程。

到目前为止我的代码:

public class httpposter {
    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://hroch486.icpf.cas.cz/cgi-bin/echo.pl");
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response2 = httpclient.execute(httpPost);
        try {
            System.out.println(response2);
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            httpPost.releaseConnection(); }} }

【问题讨论】:

  • Erm ...看到评论说“对响应正文做一些有用的事情”? hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/…
  • response2.writeTo(OutputStream); 这还能编译吗?在大多数情况下,使用getContent() 更合适。当然,响应中的内容取决于服务(可能还有请求标头)。
  • 感谢您的快速回复!这正是我想要做的,但我不确定如何访问它。所有的响应似乎都是标题信息。
  • @owlstead 我很尴尬,没有我在最后一分钟玩弄的那部分代码。抱歉,我删除了它。
  • @owlstead 我如何调用 getContent()? HttpResponse 似乎没有名为 getContent() 的方法。抱歉,我对此很陌生。

标签: java apache post


【解决方案1】:

我猜你复制并粘贴了这段代码?

HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);

Javadocs 是你的朋友:HttpEntity Javadocs

IOUtils 让这更容易:

String body = IOUtils.toString(entity2.getContent(), "UTF-8");

【讨论】:

  • 非常感谢。这是我第一次尝试这样的事情,我有点无能为力。是的,它被复制和粘贴了,我试图弄清楚如何使用它。在发布之前,我确实尝试阅读 javadocs,但这对我来说不是一个明显的解决方案。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 2019-01-23
相关资源
最近更新 更多