• HttpUtils工具类


    作为Java开发程序员,需要我们经常写一些工具类来简化开发过程,我们自己肯定写过或者用过HttpUtils用来发送http请求,但是每次手写太繁琐了,于是就按照标准写了一个Http工具类,现在分享出来。

    1.HTTP请求简介

    HTTP(Hypertest Transfer Protocol)是用于传输像HTML这样的超文本文件的应用层协议。它被设计用于WEB浏览器端和WEB服务端的交互,但也有其它用途。HTTP遵循经典的client-server模型,客户端发起请求尝试建立连接,然后等待服务端的应答。HTTP是无状态协议,这意味着服务端在两次请求间不会记录任何状态。

    2.Http请求四要素

    一个HTTP请求报文由四个部分组成:请求行、请求头部、空行、请求数据。

    1、请求行

    请求行由请求方法字段、URL字段和HTTP协议版本字段3个字段组成,它们用空格分隔。

    2、请求头部

    HTTP客户程序(例如浏览器),向服务器发送请求的时候必须指明请求类型(一般是GET或者POST)。如有必要,客户程序还可以选择发送其他的请求头。大多数请求头并不是必需的,但Content-Length除外。对于POST请求来说Content-Length必须出现。

    3、空行

    它的作用是通过一个空行,告诉服务器请求头部到此为止。

    4、请求数据

    若方法字段是GET,则此项为空,没有数据。若方法字段是POST,则通常来说此处放置的就是要提交的数据。

    HttpUtils的代码

    package com.zuoan.utils;
    
    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    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.client.utils.URIBuilder;
    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.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    public class HttpUtil {
    
        private static final CloseableHttpClient httpclient = HttpClients.createDefault();
        private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
    
        /**
         * 发送HttpGet请求
         */
        public static String sendGet(String url, String token) {
    
            String result = null;
            CloseableHttpResponse response = null;
            try {
                URIBuilder uriBuilder = new URIBuilder(url);
                HttpGet httpGet = new HttpGet(url);
                httpGet.setHeader("User-Agent", userAgent);
                httpGet.setHeader("Authorization", "token " + token);
                response = httpclient.execute(httpGet);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                }
            } catch (Exception e) {
                log.error("处理失败 {}" + e);
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
    
            }
            return result;
        }
    
        /**
         * 发送HttpGet请求,参数为map格式
         */
        public static String sendGet(String url, Map<String, String> map) {
    
            String result = null;
            CloseableHttpResponse response = null;
            try {
                URIBuilder uriBuilder = new URIBuilder(url);
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
                HttpGet httpGet = new HttpGet(uriBuilder.build());
                httpGet.setHeader("User-Agent", userAgent);
                response = httpclient.execute(httpGet);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                }
            } catch (Exception e) {
                log.error("处理失败 {}" + e);
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
    
            }
            return result;
        }
    
        /**
         * 发送HttpPost请求,参数为map
         */
        public static String sendPost(String url, Map<String, String> map) {
            // 设置参数
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 编码
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            // 设置content-type
            formEntity.setContentType("application/json");
            // 取得HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            // 防止被当成攻击添加的
            httpPost.setHeader("User-Agent", userAgent);
            // 接收参数设置
            httpPost.setHeader("Accept", "application/json");
            // 参数放入Entity
            httpPost.setEntity(formEntity);
            CloseableHttpResponse response = null;
            String result = null;
            try {
                // 执行post请求
                response = httpclient.execute(httpPost);
                // 得到entity
                HttpEntity entity = response.getEntity();
                // 得到字符串
                result = EntityUtils.toString(entity);
            } catch (IOException e) {
                log.error(e.getMessage());
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
            return result;
        }
    
        /**
         * 发送HttpPost请求,参数为json字符串
         */
        public static String sendPost(String url, String jsonStr) {
            String result = null;
            // 字符串编码
            StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
            // 设置content-type
            entity.setContentType("application/json");
            HttpPost httpPost = new HttpPost(url);
            // 防止被当成攻击添加的
            httpPost.setHeader("User-Agent", userAgent);
            // 接收参数设置
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httpPost);
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
            } catch (IOException e) {
                log.error(e.getMessage());
            } finally {
                // 关闭CloseableHttpResponse
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
            return result;
        }
    
        /**
         * 发送不带参数的HttpPost请求
         */
        public static String sendPost(String url) {
            String result = null;
            // 得到一个HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            // 防止被当成攻击添加的
            httpPost.setHeader("User-Agent", userAgent);
            CloseableHttpResponse response = null;
            try {
                // 执行HttpPost请求,并得到一个CloseableHttpResponse
                response = httpclient.execute(httpPost);
                // 从CloseableHttpResponse中拿到HttpEntity
                HttpEntity entity = response.getEntity();
                // 将HttpEntity转换为字符串
                result = EntityUtils.toString(entity);
            } catch (IOException e) {
                log.error(e.getMessage());
            } finally {
                // 关闭CloseableHttpResponse
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
            return result;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207

    若觉得文章对您有用,不妨 关注 + 收藏 哦!!更多实用文章在首页!

  • 相关阅读:
    做接口测试如何上次文件
    localhost和127.0.0.1都可以访问项目,但是本地的外网IP不能访问
    ubuntu中的系统消息中显卡显示llvmpipe (LLVM 10.0.0, 256 bits)
    基于前端技术实现的全面预算编制系统
    easyrecovery工具2023最新版一键恢复丢失数据免费下载
    进公司第二天:绿盾+TFS拉取代码
    “开启中文智能之旅:探秘超乎想象的 Llama2-Chinese 大模型世界”
    数据挖掘实践(金融风控):金融风控之贷款违约预测挑战赛(上篇)[xgboots/lightgbm/Catboost等模型]--模型融合:stacking、blending
    Java【手撕链表】LeetCode 143. “重排链表“, 图文详解思路分析 + 代码
    L1-033 出生年 c++解法
  • 原文地址:https://blog.csdn.net/weixin_45886609/article/details/134246324