篇二:HttpClient的使用
参考博客:
http://blog.csdn.net/wangpeng047/article/details/19624529
http://blog.csdn.net/zhouyingge1104/article/details/41488313
一、使用方法
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
二、功能实现
1、创建HttpClient对象
//DefaultHttpClient 过时
DefaultHttpClient —> CloseableHttpClient
HttpResponse —> CloseableHttpResponse
创建对象
CloseableHttpClient httpClient = HttpClients.createDefault();
2、get请求
public void get() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 创建httpget. HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("executing request " + httpget.getURI()); // 执行get请求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 获取响应实体 HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); // 打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { // 打印响应内容长度 System.out.println("Response content length: " + entity.getContentLength()); // 打印响应内容 System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
3、post请求
// 创建httppost HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); // 创建参数队列 List<namevaluepair> formparams = new ArrayList<namevaluepair>(); formparams.add(new BasicNameValuePair("type", "house")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } }
4、HttpResponse处理
获取请求结构码:result.getStatusLine().getStatusCode()
获取请求返回的Json字符串:EntityUtils.toString(result.getEntity(),"UTF-8")
获取参会结果字符长度:entity.getContentLength()
请求结束后,一定要关闭连接
try { if (StringUtils.isNotEmpty(params)) { //解决中文乱码问题 StringEntity entity = new StringEntity(params, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } method.setHeader("Authorization", " Basic "+auth); CloseableHttpResponse result = httpClient.execute(method); url = URLDecoder.decode(url, "UTF-8"); //返回的Code map.put("code", String.valueOf(result.getStatusLine().getStatusCode())); //返回的结果消息 map.put("message", EntityUtils.toString(result.getEntity(),"UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally{ // 关闭连接,释放资源 try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } }
三、HttpClient参数的设置
a、设置头部入参:
1、创建HttpPost 或者 HttpGet对象
2、设置参数
httpPost.addHeader("AppKey", appKey);
httpPost.addHeader("Nonce", nonce);
httpPost.addHeader("CurTime", curTime);
b、设置body请求参数
方式一:UrlEncodedFormEntity()
典型的键值对,支持传统的form表单,get和post请求都可以使用
List<NameValuePair> pairs = new ArrayList<NameValuePair>(); NameValuePair pair1 = new BasicNameValuePair("supervisor", supervisorEt.getEditableText().toString()); NameValuePair pair2 = new BasicNameValuePair("content", superviseContentEt.getEditableText().toString()); NameValuePair pair3 = new BasicNameValuePair("userId", String.valueOf(signedUser.getId())); pairs.add(pair1); pairs.add(pair2); pairs.add(pair3); httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8))
方式二:StringEntity()
传输的body是一个String的字符串,针对application/json请求
/**
*创建StringEntity时,指定body的String字符串、编码格式
*通过StringEntity设置请求的ContentType、encode
**/
StringEntity entity = new StringEntity(params, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity);

浙公网安备 33010602011771号