• 7.16Java之使用HttpClient类


    7.16Java之使用HttpClient类

    HttpClient背景

    • HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易。

    • 掌握HttpClient后,相信对于Http协议的了解会更加深入。

    org.apache.commons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别

    • Commons的HttpClient项目不再被开发

    • Apache HttpComponents项目HttpClient和HttpCore模组,提供更好的性能和更大的灵活性。

    使用HttpClient发送请求、接收响应过程

    1. 创建HttpClient对象--->关注接口是否需要带cookie值去请求。如果不需要则直接build即可

    /*不需要带cookie*/
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    /*带cookie*/
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    //再创建客户端的时候就已经带了cookie去创建对象
    //这里涉及到的是Http请求和TCP连接的内容,之前的博客已经有所说明
    1. 创建请求方法实例--->指定URL--->如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

    HttpPost httpPost = new HttpPost(url);
    1. 创建请求参数

      1. 调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;

      2. HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

    //先创造容器存放参数
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    /*
    这个NameValuePair是一个接口,里面提供了两个抽象方法:
    getName
    getValue
    这是一个设计模式
    */


    //实例化BasicNameValuePair类的引用--->注意这个构造器
    NameValuePair nameValuePair = new BasicNameValuePair("",  "");
    /*
    构造器里面有两个传参:
    1、传递两个String的值
    2、第一个String会调用args类里面的notNull方法,重新创建源码。该方法会判断传参,如果传参不为空就返回参数本身。如果传参为空返回提示语
    3、构造器对于第二个String是直接返回该值
    所以再BasicNameValuePair实例化下传递需要的参数的key和value
    */


    //将创建好的参数放入到容器中
    params.add(nameValuePair);
    1. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

    //传参的第一步是将参数拼接成完整的内容--->使用JSON(alibaba的包)下的toJSONString方法,将容器对象转为字符串--->该方法传入一个Object根类对象,返回一个String值
    String jsonString = JSON.toJSONString(params);


    //再调用String实体类将字符串转为实体字符串引用
    /*
    这个类的构造器传入两个字符量:
    1、字符串
    2、字符集编码
    字符集编码会将传入的字符串参数转为另一个编码参数--->源码内部调用了很多东西,这里不做展开
    */
    StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");


    //调用HttpClient类的setEntity方法设置传参实体--->这个方法的形参是传入一个Http实体,返回传入的实体对象
    httpPost.setEntity(stringEntity);

    //调用HttpClient类下的setHeader方法设置Content-Type的类型--->这个方法传递两个形参字符串的值
    /*
    第一个字符串会调用IDEA的方法判断是否为空,不为空返回一个值
    第二个字符串会调用内部的updateHeader去将第二个字符串的内容添加到headers后面
    一个key-value的底层实现
    */

    //调用execute方法发送本次请求
    httpClient.execute(httpPost);
    //这样就发送了本次httpPost请求
    1. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;

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

    //创建响应模型
    CloseableHttpResponse response = null;
    //新建一个HttpEntity接口的引用对象,该接口可以调用相应模型中的getContentType方法,该方法返回一个HttpEntity值
    HttpEntity responseEntity = response.getEntity();
    //这样就拿到的响应的实体
    //接下来的处理就是调用HttpEntity类下提供的方法获取实体的内容
    System.out.println("响应状态为:" + responseEntity.getContentLength());
               //判断
               if (responseEntity!=null){
                   System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                   System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
              }
    完整的请求代码
    package OmsOrdersPullInterface;

    import com.alibaba.fastjson.JSON;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.BasicCookieStore;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.cookie.BasicClientCookie;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;

    import java.util.ArrayList;
    import java.util.List;

    /**
    * 测试订单拉取接口问题
    * @since JDK 1.8
    * @date 2021/07/16
    * @author Lucifer
    */
    public class omsOrdersPullInterface {
       /*
       Content-Type:x-www-form-urlencoded
        */
       //定义接口地址
       private static final String Url = "http://oms.spocoo.com/v1/orders/index/pull.html";
       //Cookie值
       public static String Cookie = "is_show_search=1;" +
               "_ati=5995140554762;" +
               "_ga=GA1.2.69664751.1620351776;" +
               "users=Pe5XXPUBxTPbVMlNcrItqq8zw_TdG4XMPUyhT-eKh2J7lD45f7Bj17mkI01TgmSMZ2yS41_avK_7p4xPF6q77hmtzhNs_DzeTLMZpndc0_mIgvJbbEt_idqAzXU8luW9sypFYV_dx9PSktF4Pt2Vc0_y-nHWmCf_JdhwInPiqF3Agit6XwQ7T-n1rbQnvjJyIFU1kTqcMlE698Y5qD4um6IZq4ZaBceHJHCrsFkj9Yds5E-Mjt843kEJapHyVAtj2FwZWs7uupVj4BlpWpQWHXKCaskGp0cyLbRQk4RJSYFqzOpghyidiU4hau2X5pRA16u5KKPvWxsHcOOp6egYL3lvG3wVqlyXsTHdX4DLatu6YJZuAqSoZiwrNndYRNt2GD7hUspoF-EoSR9LiCBhoQ;" +
               "think_var=zh-cn;" +
               "PHPSESSID=d948c1d3f915007cea083937eeeed29c";
       /**
        *用HttpClient类下的方法创建POST请求demo
        * Content-Type:x-www-form-urlencoded
        */
       public static void doPostPullOrders(String url){
           //创建Cookie存储
           CookieStore cookieStore = new BasicCookieStore();
           //设置Cookie值
           BasicClientCookie cookie = new BasicClientCookie("Cookie", Cookie);
           cookie.setDomain("oms.spocoo.com");
           cookie.setPath("/");
           //将Cookie放入cookie存储中
           cookieStore.addCookie(cookie);
           //使用HttpClient创建客户端
           CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
           //创建httppost类引用
           HttpPost httpPost = new HttpPost(url);
           /*这个httpPost既是我们的表单,创建表单参数*/
           List<NameValuePair> params = new ArrayList<NameValuePair>();

           //创建参数
           /*
           platform=real&platform_accountid=17978&startTime=2021-07-10&endTime=2021-07-16&orderid=MXLTPFD
            */
           NameValuePair nameValuePair = new BasicNameValuePair("platform",  "real");
           NameValuePair nameValuePair1 = new BasicNameValuePair("platform_accountid", "17978");
           NameValuePair nameValuePair2 = new BasicNameValuePair("startTime", "2021-07-10");
           NameValuePair nameValuePair3 = new BasicNameValuePair("endTime", "2021-07-16");
           NameValuePair nameValuePair4 = new BasicNameValuePair("orderid", "");

           //在List引用里面添加参数
           params.add(nameValuePair);
           params.add(nameValuePair1);
           params.add(nameValuePair2);
           params.add(nameValuePair3);
           params.add(nameValuePair4);

           System.out.println(params);

           //传参
           String jsonString = JSON.toJSONString(params);
           System.out.println(jsonString);
           StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");

           //将实体放入post请求体中
           httpPost.setEntity(stringEntity);
           httpPost.setHeader("Content-Type", "x-www-form-urlencoded");

           //响应模型--->通过请求对象获取响应对象
           CloseableHttpResponse response = null;
           try {
               //由客户端执行发送Post请求
               response = httpClient.execute(httpPost);
               //从响应模型中获得响应实体
               HttpEntity responseEntity = response.getEntity();
               //获取报文里data参数
               String JSONdata = JSON.toJSONString(responseEntity.getContentType());
               //打印响应状态
               System.out.println("响应状态为:" + responseEntity.getContentLength());
               //判断
               if (responseEntity!=null){
                   System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                   System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
              }
          }catch (Exception e){
               System.out.println(e.getMessage());
               e.printStackTrace();
          }finally {
               //关闭资源
               try {
                   //判断客户端实体
                   if (httpClient != null) {
                       httpClient.close();
                  }
                   //判断响应实体
                   if (response != null) {
                       response.close();
                  }
              }catch (Exception e){
                   System.out.println(e.getMessage());
                   e.printStackTrace();
              }
          }
      }

       public static void main(String[] args) {
           doPostPullOrders(Url);
      }
    }
    It's a lonely road!!!
  • 相关阅读:
    算法与数据结构9
    算法与数据结构8
    数据结构与算法7
    数据结构与算法6
    计算机视觉(七)
    计算机视觉(六)
    计算机视觉(五)
    vscode 创建java项目
    vue 访问API接口
    vscode+vue 框架搭建
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15021733.html
Copyright © 2020-2023  润新知