开发者

java使用httpclient 发送请求的示例

目录
  • 一、使用的Jar包
  • 二、接口代码
    • Get的无参/有参请求
  • 三、使用的类
    • 四、标准字符集的常量定义
      • 五、请求状态常量

        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;
        }

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

        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": "未公布",

              &qu编程ot;sure_present": 3108

            },

            "history": {

              "sure_cnt": 10452,

              "cure_cnt": 7337,

              "die_cnt": 7

            },

         javascript;   "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, javascriptnull);
        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);

        请求结果:

        java使用httpclient 发送请求的示例

        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;
        // 200python
        HttpStatus.SC_OK

        到此这篇关于java使用httpclient 发送请求的文章就介绍到这了,更多相关httpclient 发送请求内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

        0

        上一篇:

        下一篇:

        精彩评论

        暂无评论...
        验证码 换一张
        取 消

        最新开发

        开发排行榜