Apache HTTPClient 的使用

前言

下面介绍Apache HTTPClient 的使用方式。

依赖包

  • httpclient-4.5.13.jar
  • commons-codec-1.15.jar
  • commons-logging-1.2.jar
  • httpcore-4.4.15.jar

备注:依赖包可以去 maven仓库下载。

1、GET请求

   // 创建客户端请求
   CloseableHttpClient client = HttpClientBuilder.create().build();
   // 创建GET请求
   HttpGet get = new HttpGet("http://10.47.22.151:8100/api/Login/UserToken");
   // 执行GET请求
   CloseableHttpResponse response = client.execute(get);

   try {
       // 获取请求内容
       HttpEntity entity = response.getEntity();
       System.out.println(EntityUtils.toString(entity));
   } finally {
       if (response != null) {
           response.close();
       }
       if (client != null) {
           client.close();
       }
   }

2、POST

1)Params类型
  // 创建客户端请求
  CloseableHttpClient client = HttpClientBuilder.create().build();
  // 创建POST请求
  HttpPost post = new HttpPost("http://10.147.254.110:80/token");
  // 拼接参数
  List<NameValuePair> list = new ArrayList<>();
  list.add(new BasicNameValuePair("userName", "rest"));
  list.add(new BasicNameValuePair("password", "123456"));
  list.add(new BasicNameValuePair("loginName", "jack"));
  // 设置请求头
  post.setHeader("Content-Type", "application/json");
  // 设置请求参数
  post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
  // 执行请求
  CloseableHttpResponse response = client.execute(post);
  try {
      // 获取请求内容
      HttpEntity entity = response.getEntity();
      System.out.println(EntityUtils.toString(entity));
  } finally {
      if (response != null) {
          response.close();
      }
      if (client != null) {
          client.close();
      }
  }
2)row类型
   // 创建客户端请求
   CloseableHttpClient client = HttpClientBuilder.create().build();
   // 创建POST请求
   HttpPost post = new HttpPost("http://10.147.254.110:80/seeyon/rest/token");
   // 拼接参数
   Map<String, String> rMap = new HashMap<>();
   rMap.put("userName", "rest");
   rMap.put("password", "991dfd4a-d7bb-4aa6-b04c-d1a1bff26d4f");
   rMap.put("loginName", "lyb");
   // 设置请求头
   post.setHeader("Content-Type", "application/json");
   // 设置请求参数
   post.setEntity(new StringEntity(JSON.toJSONString(rMap)));
   // 执行请求
   CloseableHttpResponse response = client.execute(post);
   try {
       // 获取请求内容
       HttpEntity entity = response.getEntity();
       System.out.println(EntityUtils.toString(entity));
   } finally {
       if (response != null) {
           response.close();
       }
       if (client != null) {
           client.close();
       }
   }

以上 ·params· 和 ·raw· 是对应 postman中的两种传参方式。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值