2015-05-19 57 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(); 
    } 
} 

}