HttpClient详解(6大功能及使用流程实例)

HttpClient详解(6大功能及使用流程实例)-mikechen

HttpClient定义

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包。

 

HttpClient作用

HTTP Client和浏览器有点像,都可以用来发送请求,接收服务端响应的数据,但它不是浏览器,没有用户界面,只通过其API用于传输和接受HTTP消息。

 

HttpClient功能

HttpClient的主要功能,包含如下:

  • 基于标准的java语言实现了Http1.0和Http1.1等;
  • 实现了所有 HTTP 的方法,比如:GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等;
  • 支持 HTTPS 协议;
  • 支持代理服务器,比如:Nginx等;
  • 支持自动跳转转向等;

 

HttpClient使用步骤

使用HttpClient发送请求接收响应很简单,一般需要如下六步即可:

第一步: 创建HttpClient对象

  1. CloseableHttpClient HttpClient = HttpClientBuilder.create().build();

提示:推荐用CloseableHttpClient,HttpClient是历史遗留版本,官方推荐使用CloseableHttpClient

 

第二步:创建请求方法的实例,并指定请求URL。

如果需要发送GET请求,创建HttpGet对象。

  1. HttpGet httpGet = new HttpGet("https://mikechen.cc");

如果需要发送POST请求,创建HttpPost对象。

  1. HttpPost httppost = new HttpPost("https://mikechen.cc");

 

第三步:设置发送请求参数

如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数。

 

第四步:调用execute发送请求

  1. HttpResponse response = HttpClient.execute(httpGet);

发送请求,该方法返回一个HttpResponse。

 

第五步:获取请求内容

调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。

  1. //调用HttpResponse的getEntity()方法可获取HttpEntity对象           
  2. HttpEntity resEntity = response.getEntity();

调用HttpResponse的getEntity()方法,程序可通过该对象获取服务器的响应内容。

 

第六步:释放连接

  1. response.close();
  2. HttpClient.close();

无论执行方法是否成功,都必须释放连接。

 

HttpClient使用实例

下面我们一起再看下完整的HttpClient使用实例。

1.添加HttpClient依赖

  1. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/HttpClient -->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents</groupId>
  4. <artifactId>HttpClient</artifactId>
  5. <version>5.2</version>
  6. </dependency>

 

2.发送GET请求

HttpClient发送GET请求的例子,如下所示:

  1. public void doGetTestOne() {
  2. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
  3. CloseableHttpClient HttpClient = HttpClientBuilder.create().build();
  4. // 创建Get请求
  5. HttpGet httpGet = new HttpGet("https://mikechen.cc/item/1/31661");
  6. // 响应模型
  7. CloseableHttpResponse response = null;
  8. try {
  9. // 由客户端执行(发送)Get请求
  10. response = HttpClient.execute(httpGet);
  11. // 从响应模型中获取响应实体
  12. HttpEntity responseEntity = response.getEntity();
  13. System.out.println("响应状态为:" + response.getStatusLine());
  14. if (responseEntity != null) {
  15. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
  16. System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
  17. }
  18. } catch (ClientProtocolException e) {
  19. e.printStackTrace();
  20. } catch (ParseException e) {
  21. e.printStackTrace();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. } finally {
  25. try {
  26. // 释放资源
  27. if (HttpClient != null) {
  28. HttpClient.close();
  29. }
  30. if (response != null) {
  31. response.close();
  32. }
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }

GET请求的参数传递是通过URL拼接来实现的,所以,我们想发送带参数的Get请求,可直接拼接在ulr后。

 

3.发送POST请求

  1. /*
  2. * 封装HttpClient发送post请求的工具类
  3. * */
  4. public class HttpClientUtils {
  5. //私有化构造器,防止HttpClientUtils被创建对象
  6. private HttpClientUtils(){
  7. }
  8. static CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
  9.  
  10. //HttpPost的请求执行
  11. public static String sendHttpPost(String url, JSONObject JsonValues) throws UnsupportedEncodingException {
  12. HttpClientUtils = HttpClientUtils.getHttpClientUtils();
  13. //获取HttpPost
  14. HttpPost httpPost = new HttpPost(url);
  15. //设置请求头
  16. httpPost.setHeader("x-appid", "test");
  17. httpPost.setHeader("x-client-version", "4.0.0");
  18. httpPost.setHeader("Content-Type","application/json");
  19. // 设置请求体
  20. StringEntity entity = new StringEntity(JsonValues.toString());
  21. httpPost.setEntity(entity);
  22. String content = null;
  23. try {
  24. CloseableHttpResponse responseTest = closeableHttpClient.execute(httpPost);
  25. if (responseTest.getStatusLine().getStatusCode() == 200) {
  26. // 获取响应实体
  27. HttpEntity resTestEntity = responseTest.getEntity();
  28. // 输出响应
  29. content = EntityUtils.toString(resTestEntity, "utf-8");
  30. }else {
  31.  
  32. System.out.println("无效请求");
  33. }
  34. responseTest.close();
  35.  
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. try {
  40. closeableHttpClient.close();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. return content;
  45. }
  46. }

 

评论交流
    说说你的看法
欢迎您,新朋友,感谢参与互动!