httpclient(一)
httpclient是apache封装的用于http请求的工具包,和python的requests类似。这里介绍一些简单功能的使用。后续根据需求也会慢慢扩展
使用HttpClient请求一个Http请求的步骤为:
(1)创建一个HttpClient对象模拟浏览器操作
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
(2)创建一个Request对象
HttpGet get = new HttpGet(url);
HttpPost post = new HttpPost(url);
(3)头部参数处理
get.addHeader("1","2");
post.addHeader("1","2");
(4)参数处理
普通data参数处理
List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair(parameter[0],parameter[1])); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); post.setEntity(entity);
json格式处理
StringEntity entity = new StringEntity(json,"utf-8"); entity.setContentType("text/json"); entity.setContentEncoding("UTF-8"); post.addHeader("Content-type", "application/json;charset=UTF-8"); post.setEntity(entity);
(5)发送http请求,获得返回值
CloseableHttpResponse resp = httpClient.execute(post);
CloseableHttpResponse resp = httpClient.execute(get);
(4)处理response
HttpEntity httpEntity = resp.getEntity();
String result = EntityUtils.toString(httpEntity, "utf-8");
(5)关闭HttpClient
httpClient.close();
package apitest; import java.io.IOException; import java.text.ParseException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class TestHpptClient { public static void main(String[] args) { doGetTestOne(); } public static void doGetTestOne() { // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //创建一个Request对象 HttpGet httpGet = new HttpGet("http://118.24.13.38:8080/goods/UserServlet?method=loginMobile&loginname=test1&loginpass=test1"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } }