【发布时间】: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() 的方法。抱歉,我对此很陌生。