2012-12-30 2 views
2

Java에서 HttpComponents를 사용하여 로그인 정보를 웹 사이트에 게시합니다. 로그인 한 후 반환 된 웹 페이지에 따라 더 많은 POST 데이터를 보내고 싶습니다. 나는 실제로 출력하거나 html/웹 페이지를 보는 방법을 잘 모르겠다. 서버가 내 POST 데이터를 전송 한 결과로 리턴한다. (아마 내가 찾고있는 것이 응답 본문 일까?).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

음 ... "응답 본체와 유용한 무언가를"라는 주석을 참조

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

Javadoc과 당신의 친구입니까? http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html –

+0

'response2.writeTo (OutputStream);'심지어 컴파일됩니까? 대부분의 상황에서'getContent()'를 사용하는 것이 더 적절합니다. 물론 응답 내용은 서비스 (및 요청 헤더)에 따라 다릅니다. –

+0

빠른 응답을 보내 주셔서 감사합니다. 그것이 정확하게 내가하려는 일이지만, 어떻게 접근해야하는지 확신 할 수 없습니다. 모든 응답은 헤더 정보입니다. – user1762250

답변

3

난 당신이 복사하고이 코드를 붙여 같은데요? HttpEntity Javadocs

IOUtils이 더욱 쉽게 :

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

정말 고마워요. 이런 것은 처음 시도하는 것이고 나는 거의 우둔한 사람이 아닙니다. 예, 복사하여 붙여 넣었습니다. 사용 방법을 알아 내려고했습니다. 게시하기 전에 javadocs를 읽으려고했으나 이것은 나에게 명백한 해결책이 아니 었습니다. 다시 한 번 감사드립니다! – user1762250

관련 문제