java使用httpclient 发送请求的示例

 更新时间:2023年10月19日 11:54:23   作者:有梦想的菜  
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议,这篇文章主要介绍了java使用httpclient 发送请求的示例,需要的朋友可以参考下

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

一、使用的Jar包

首先需要在maven中引入如下包

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.13</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>2.0.18</version>
</dependency>

二、接口代码

Get的无参/有参请求

/**
 * @param url     接口地址
 * @param headers 请求头
 * @Description get请求
 */
public static String getData(String url, Map<String, String> headers) {
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    if (headers != null && !headers.isEmpty()) {
        for (String head : headers.keySet()) {
            httpGet.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try {
        response = closeableHttpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8).trim();
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
        StringResult = "errorException:" + e.getMessage();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null) {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return StringResult;
}

请求实列:在这里无参请求就不展示,可自行试验

Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
String data = getData("https://api.vvhan.com/api/covid?city=重庆", headers);
System.out.println(data);

请求结果:

{
  "success": true,
  "data": {
    "updatetime": "2022-12-23 09:46:10",
    "country": "中国",
    "province": "重庆",
    "city": "重庆",
    "now": {
      "sure_new_loc": "未公布",
      "sure_new_hid": "未公布",
      "sure_present": 3108
    },
    "history": {
      "sure_cnt": 10452,
      "cure_cnt": 7337,
      "die_cnt": 7
    },
    "danger": {
      "high_risk": 0,
      "medium_risk": 0
    }
  }
}

Post请求(application/x-www-form-urlencoded)

/**
 * @param url     接口地址
 * @param list    NameValuePair(简单名称值对节点类型)类似html中的input
 * @param headers 请求头(默认Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
 * @Description post请求
 */
public static String postData(String url, ArrayList<NameValuePair> list, Map<String, String> headers) {
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    if (list != null && !list.isEmpty()) {
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
        httpPost.setEntity(formEntity);
    }
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    if (headers != null && !headers.isEmpty()) {
        for (String head : headers.keySet()) {
            httpPost.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try {
        response = closeableHttpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        EntityUtils.consume(entity);
    } catch (Exception e) {
        StringResult = "errorException:" + e.getMessage();
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null) {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return StringResult;
}

请求实列:

ArrayList<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", "用户名"));
list.add(new BasicNameValuePair("password", "1234"));
String s = postData("http://127.0.0.1:3000/aaa/file/testPost.jsp", list, null);
System.out.println(s);

请求结果:

用户名
1234
application/x-www-form-urlencoded; charset=UTF-8

Post请求(application/json)

/**
 * @param url        接口地址
 * @param jsonString json字符串
 * @param headers    请求头(默认Content-Type:application/json; charset=UTF-8)
 * @Description post Json 请求
 */
public static String postJsonData(String url, @NotNull String jsonString, Map<String, String> headers) {
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    StringEntity jsonEntity = new StringEntity(jsonString, Consts.UTF_8);
    jsonEntity.setContentEncoding(Consts.UTF_8.name());
    httpPost.setEntity(jsonEntity);
    httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
    if (headers != null && !headers.isEmpty()) {
        for (String head : headers.keySet()) {
            httpPost.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try {
        response = closeableHttpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        EntityUtils.consume(entity);
    } catch (Exception e) {
        StringResult = "errorException:" + e.getMessage();
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null) {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return StringResult;
}

请求实列:

JSONObject jsonObject = new JSONObject();
jsonObject.put("demo", "456789");
jsonObject.put("demo1", "哈哈哈爱发火");
String s = postJsonData("http://127.0.0.1:3000/api/workflow/v1/insert2", jsonObject.toJSONString(), null);
System.out.println(s);

请求结果:

Get请求url拼接

/**
 * @param url    接口地址(无参数/有参)
 * @param params 拼接参数集合
 * @Description get请求URL拼接参数 & URL编码
 */
public static String getAppendUrl(String url, Map<String, String> params) {
    StringBuffer buffer = new StringBuffer(url);
    if (params != null && !params.isEmpty()) {
        for (String key : params.keySet()) {
            if (buffer.indexOf("?") >= 0) {
                buffer.append("&");
            } else {
                buffer.append("?");
            }
            String value = "";
            try {
                value = URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            buffer.append(key)
                    .append("=")
                    .append(value);
        }
    }
    return buffer.toString();
}

请求实列:

Map<String, String> params = new HashMap<>();
params.put("city", "重庆");
params.put("number", "手机号");
String appendUrl = getAppendUrl("https://TestGetSplice/index", params);
String appendUrl1 = getAppendUrl("https://TestGetSplice/index?a=33", params);
System.out.println(appendUrl);
System.out.println(appendUrl1);

请求结果:

https://TestGetSplice/index?number=%E6%89%8B%E6%9C%BA%E5%8F%B7&city=%E9%87%8D%E5%BA%86
https://TestGetSplice/index?a=33&number=%E6%89%8B%E6%9C%BA%E5%8F%B7&city=%E9%87%8D%E5%BA%86

三、使用的类

import com.alibaba.fastjson.JSONObject;
import com.sun.istack.internal.NotNull;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

四、标准字符集的常量定义

这些字符集保证在Java平台的每个实现上都可用。

import java.nio.charset.StandardCharsets;
StandardCharsets.UTF_8

五、请求状态常量

import org.apache.http.HttpStatus;
// 200
HttpStatus.SC_OK

到此这篇关于java使用httpclient 发送请求的文章就介绍到这了,更多相关httpclient 发送请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java使用DFA算法实现过滤多家公司自定义敏感字功能详解

    Java使用DFA算法实现过滤多家公司自定义敏感字功能详解

    这篇文章主要介绍了Java使用DFA算法实现过滤多家公司自定义敏感字功能,结合实例形式分析了DFA算法的实现原理及过滤敏感字的相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • Java List 用法详解及实例分析

    Java List 用法详解及实例分析

    这篇文章主要介绍了Java List 用法详解及实例分析的相关资料,需要的朋友可以参考下
    2017-07-07
  • JAVA程序内存溢出问题原因分析

    JAVA程序内存溢出问题原因分析

    这篇文章主要介绍了JAVA程序内存溢出问题原因,较为详细的分析java导致程序内存溢出的原因与解决方法,需要的朋友可以参考下
    2015-06-06
  • springboot-curd基于mybatis项目搭建

    springboot-curd基于mybatis项目搭建

    这篇文章主要介绍了springboot-curd基于mybatis项目搭建,围绕相关资料展开详细内容,希望对正在学习的你有所帮助,需要的小伙伴也可以参考一下
    2022-01-01
  • Java 停止线程需要注意的地方

    Java 停止线程需要注意的地方

    这篇文章主要介绍了Java 停止线程需要注意的地方,帮助大家更好的理解和学习Java线程的相关资料,感兴趣的朋友可以了解下
    2020-09-09
  • SpringCloud 服务注册中的nacos实现过程

    SpringCloud 服务注册中的nacos实现过程

    这篇文章主要介绍了SpringCloud 服务注册之nacos实现过程,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • 关于SpringBoot集成Lettuce连接Redis的方法和案例

    关于SpringBoot集成Lettuce连接Redis的方法和案例

    这篇文章主要介绍了关于SpringBoot集成Lettuce连接Redis的方法和案例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Java将word文件转成pdf文件的操作方法

    Java将word文件转成pdf文件的操作方法

    这篇文章主要介绍了Java将word文件转成pdf文件的操作方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-09-09
  • 详解JavaSE实现IoC

    详解JavaSE实现IoC

    简单地说,IoC 是反转控制,类似于好莱坞原则,主要有依赖查找和依赖注入实现。依赖查找是主动或手动的依赖查找方式,通常需要依赖容器或标准API实现。 而依赖注入则是手动或自动依赖绑定的方式,无需依赖特定的容器和API。本文将详细介绍JavaSE实现IoC。
    2021-06-06
  • 详解Java中AC自动机的原理与实现

    详解Java中AC自动机的原理与实现

    AC自动机是一个多模式匹配算法,在模式匹配领域被广泛应用。本文将详细为大家介绍AC自动机的原理与实现方法,感兴趣的可以了解一下
    2022-05-05

最新评论