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)
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于