2012-12-30 42 views
2

我使用Java中的HttpComponents將登錄信息發佈到網站。登錄後,我想發送更多POST數據,具體取決於返回的網頁。我不確定如何實際打印或查看服務器由於發送我的POST數據而返回的html /網頁(也許我正在尋找的是響應主體?)。Java Apache HttpComponents,如何讀取POST響應?

所有的教程似乎只顯示如何查看標題信息或服務器代碼。我認爲這可能是我錯過的簡單東西。也許我可能不太瞭解這個過程。

我迄今爲止代碼:

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(); }} } 
+1

呃......看,說:「做一些與響應身體有益」的評論? http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html –

+0

'response2.writeTo(OutputStream);'這是否甚至編譯?在大多數情況下使用'getContent()'更合適。當然,響應中的內容取決於服務(可能還有請求標頭)。 –

+0

感謝您的快速響應!這正是我想要做的,但我不確定如何訪問它。所有的答覆似乎都是標題信息。 – user1762250

回答

3

我猜你複製並粘貼這個代碼?

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

的Javadoc是你的朋友:HttpEntity Javadocs

IOUtils使這更容易:

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

非常感謝。這是我第一次嘗試這樣的事情,而且我有點無知。是的,它被複制和粘貼,我試圖找出如何使用它。我在發佈之前嘗試閱讀javadoc,但這對我來說不是一個明顯的解決方案。再次感謝! – user1762250

相關問題