zoukankan      html  css  js  c++  java
  • 7.19Java之HttpClient类发送GET请求方法

    7.19Java之HttpClient类发送GET请求方法

    步骤

    先创建请求携带的必要信息

    GET请求是将参数拼接成字符串加上"?"带上参数去请求服务器的:

    • 直接再String参数后 + "?" + params

    • 先列出params然后使用指定类下的构造器将参数拼接成字符串

    直接通过url传参--->这里使用的不是JDK提供的URL类,而是alibaba提供的HttpClient类

    创建客户端:

    //创建客户端
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    创建Cookie存储:

    //这是一个Cookie接口,里面提供了getCookie的方法
    CookieStore cookieStore = new BasicCookieStore();
    //BasicCookieStore是一个实现了CookieStore的类

    构造发送GET请求的需要携带的参数--->包括Cookie等

    //设置Cookie值
               BasicClientCookie basicClientCookie = new BasicClientCookie("Cookie", cookie);
    /*
    BasicClientCookie类实现了众多Cookie接口,提供了构造器。返回一个Map的hash值
    */
               //设置Cookie的域
               basicClientCookie.setDomain("");
               //设置Cookie路径
               basicClientCookie.setPath("/");
               //将设置好的Cookie放入接口引用中
               cookieStore.addCookie(basicClientCookie);

    创建响应实体接收响应内容:

    //创建响应实体
               CloseableHttpResponse response = null;
               try {
                   //从响应模型中获得实体对象
                   HttpEntity responseEntity = response.getEntity();
                   //对实体对象进行判断
                   if (responseEntity == null){
                       System.out.println("响应实体对象为空!");
                       throw new IOException();
                  }else {
                       //打印实体状态
                       System.out.println("响应状态为:" + responseEntity.getContentType());
                       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();
                  }
              }
          } catch (ClientProtocolException e) {
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
          }
    使用GET方式进行传参(直接拼接URL)
    package OmsInformationInterface;

    import org.apache.http.HttpEntity;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    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.util.EntityUtils;
    import org.testng.annotations.Test;

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;

    /**
    * 调用OMS订单信息订单信息获取接口获取到订单信息
    * @since JDK 1.8
    * @date 2021/07/20
    * @author Lucifer
    */
    public class OmsOrdersGetInformation {
       //定义接口Url
       private static final String Url = "";
       //拿到Cookie
       private static final String Cookie = "";

       /*Get方法*/
       @Test
       public static void doGetInformation(String url, String cookie){
           //建立Cookie存储
           CookieStore cookieStore = new BasicCookieStore();
           //新建Http客户端
           CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
           //--->使用StringBuffer类进行字符拼接
           StringBuffer params = new StringBuffer();

           //创建连接参数
           try {
               /*字符数据编码一下,否则可能无法传过去--->encoding*/
               params.append("dotype=" + URLEncoder.encode("1", "utf-8"));
               params.append("end_time=2021-05-25" + URLEncoder.encode("%%2023:59:59", "utf-8"));
               params.append("index_type=1");
          }catch (UnsupportedEncodingException e){
               System.out.println(e.getMessage());
               e.printStackTrace();
          }

           /*发送GET请求*/
           try {
               //创建get请求
               HttpGet httpGet = new HttpGet(url + "?" + params);
               //创建Cookie
               BasicClientCookie Cookie = new BasicClientCookie("Cookie", cookie);
               //设置域
               Cookie.setDomain("");
               //设置路径
               Cookie.setPath("/");
               //将设置好的Cookie放入接口引用中
               cookieStore.addCookie(Cookie);
               //创建响应模型,接收返回的响应实体
               CloseableHttpResponse response = null; //未初始化
               try {
                   //配置信息
                   RequestConfig requestConfig = RequestConfig.custom()
                           //设置连接超时时间(毫秒)
                  .setConnectionRequestTimeout(5000)
                           //设置socket读写超时的时间
                  .setSocketTimeout(5000)
                           //设置是否允许重定向
                  .setRedirectsEnabled(true).build();

                   //将配置信息放入Get请求中
                   httpGet.setConfig(requestConfig);

                   //响应模型接收这个请求
                   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();
              }
          }catch (Exception e){
               System.out.println(e.getMessage());
               e.printStackTrace();
          }
      }

       public static void main(String[] args) {
           doGetInformation(Url, Cookie);
      }
    }
    使用json方式进行传参
     //json方式--->使用的是net.sf.json库
            JSONObject jsonParam = new JSONObject();  
            jsonParam.put("name", "admin");
            jsonParam.put("pass", "123456");
            StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题--->关键在于将字符串实体放入到POST请求体中
            entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");    
            httpPost.setEntity(entity);
    使用表单的方式进行传参
    //表单方式--->这里面要区分两种具体的表单传参方式
    /*
    1、将参数组成字符串放入body中再拼接到url后面类似get方式传参
    2、将参数拼接成表单放入form中在传递
    */
    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
           pairList.add(new BasicNameValuePair("name", "admin"));
           pairList.add(new BasicNameValuePair("pass", "123456"));
           httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
    //设置编码,避免出现中文错乱

    注意:

    • 再Build客户端的时候这个就需要设置Cookie值了

    It's a lonely road!!!
  • 相关阅读:
    Delphi XE10编写的《海康摄像机SDK测试DEMO》
    Delphi XE10编写的《开放式公路收费系统》
    Delphi XE7 用indy开发微信公众平台所有功能,可刷阅读,可刷赞,可加推广(除微支付)
    Delphi XE7 用indy开发微信公众平台(9)- 高级群发接口
    Delphi XE7 用indy开发微信公众平台(8)- 自定义菜单
    Delphi XE7 用indy开发微信公众平台(7)- 用户管理
    Delphi XE7 用indy开发微信公众平台(6)- 被动回复用户消息
    Delphi XE7 用indy开发微信公众平台(5)- 接收事件推送
    Delphi XE7 用indy开发微信公众平台(4)- 接收普通消息
    Delphi XE7 用indy开发微信公众平台(3)- 验证消息真实性
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15042535.html
Copyright © 2011-2022 走看看