2015-05-19 59 views
0

我試圖用HTTP POST動作的響應主體的工作,我採取了以下方法:問題Apache的HttpClient的越來越響應當

公共類POST2 {

public final static void main(String[] args) throws Exception { 

     CloseableHttpClient httpclient = HttpClients.createDefault(); 

     List<NameValuePair> formparams = new ArrayList <NameValuePair>(); 
     formparams.add(new BasicNameValuePair("login_id", myID)); 
     formparams.add(new BasicNameValuePair("api_key", myKey)); 
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); 
     HttpPost httppost = new HttpPost(myURL); 
     httppost.setEntity(entity); 

     CloseableHttpResponse response2 = httpclient.execute(httppost); 

     try{ 

      System.out.println(response2.getStatusLine()); 
      HttpEntity entity2 = response2.getEntity(); 
      EntityUtils.consume(entity2); 

      String responseBody = EntityUtils.toString(entity2); 
      System.out.println("finalResult"+responseBody.toString()); 



     } 

     finally { 

      httpclient.close(); 
     } 
    } 

}

我只是接收 「HTTP/1.1 200 OK」,隨後

異常在線程 「主要」 java.lang.ClassCastException:org.apache.http.impl.execchain.HttpResponseProxyç annot be cast to org.apache.http.HttpEntity at post2.main(post2.java:62)

我應該如何從WebService恢復正文信息?

謝謝, 利奧

+0

得到它...不得不移動EntityUtils.consume(ENTITY2);到塊的底部... – lscesario

回答

1

不得不移動EntityUtils.consume(ENTITY2);到塊的末尾:

public final static void main(String[] args) throws Exception { 

    CloseableHttpClient httpclient = HttpClients.createDefault(); 

    List<NameValuePair> formparams = new ArrayList <NameValuePair>(); 
    formparams.add(new BasicNameValuePair("login_id", myID)); 
    formparams.add(new BasicNameValuePair("api_key", myKey)); 
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); 
    HttpPost httppost = new HttpPost(myURL); 
    httppost.setEntity(entity); 

    CloseableHttpResponse response2 = httpclient.execute(httppost); 

    try{ 

     System.out.println(response2.getStatusLine()); 
     HttpEntity entity2 = response2.getEntity(); 
     String responseBody = EntityUtils.toString(entity2); 
     System.out.println("finalResult"+responseBody.toString()); 
     EntityUtils.consume(entity2); 


    } 

    finally { 

     httpclient.close(); 
    } 
} 

}