2

我正在使用 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(); }} }
4

1 回答 1

3

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

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");
于 2012-12-30T19:20:25.643 回答