我尝试使用HTTP
POST
操作的响应正文。我正在实施以下方法:
public class 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();
}
}
}
我刚收到&#34; HTTP / 1.1 200 OK&#34;,然后是:
Exception in thread "main" java.lang.ClassCastException: org.apache.http.impl.execchain.HttpResponseProxy cannot be cast to org.apache.http.HttpEntity
at post2.main(post2.java:62)
我应该如何从WebService恢复身体信息?
谢谢, 利奥
答案 0 :(得分: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();
}
}