栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Apache HTTPClient 的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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 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中的两种传参方式。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/895213.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号