K 的博客

记录精彩的程序人生 开始使用

Apache HttpClient 基本用法

GET:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
     //读取流
     InputStream instream = entity.getContent();
     //读取字符串
     String rpString=EntityUtils.toString(entity);
     //读取字节
     byte[] btArray=EntityUtils.toByteArray(httpentity);
    //请求关闭
    httpget.abort();
    //另一种关闭方式
    //httpclient.getConnectionManager().shutdown();
 }
 

 POST:

  /*ClientConnectionManager connManager = new PoolingClientConnectionManager();
  DefaultHttpClient client = new DefaultHttpClient(connManager);*/

HttpClient httpclient = new DefaultHttpClient();
/MultipartEntity entity = new MultipartEntity();
entity.addPart("name", new StringBody("important message", Charset.forName("UTF-8")));
/
StringEntity entity = new StringEntity("important message","text/plain; charset="UTF-8"");
entity.setChunked(true);
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity httpentity = response.getEntity();

if (httpentity != null) {
//读取流
InputStream instream = entity.getContent();
//读取字符串
String rpString=EntityUtils.toString(entity);
//读取字节
byte[] btArray=EntityUtils.toByteArray(httpentity);
//请求关闭
httpget.abort();
//另一种关闭方式
//httpclient.getConnectionManager().shutdown();
}

异常处理 non-repeatable entity

MultipartEntity entity = new MultipartEntity();
//这段代码可能是导致异常的 原因
entity.addPart("image", new InputStreamBody(new FileInputStream(new File("D:/httpclient/images/0.jpg");), file.getName()));

org.apache.http.client.ClientProtocolException
Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity. The cause lists the reason the original request failed.

HttpClient有ByteArrayBody、FileBody、InputStreamBody和StringBody四种Body。经过测试,其中只有用InputStreamBody构建multipartEntity才是non-repeatable entity。
使用ByteArrayBody代替InputStreamBody 避免错误

 

异常处理 请求超时

java.net.SocketTimeoutException: Read timed out
DefaultHttpClient: //请求超时 httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); //读取超时 httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

HttpClient
HttpClient httpClient=new HttpClient();
//链接超时
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
//读取超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000)

 

评论
留下你的脚步