• Java工具类:HttpUtil项目实战


    • 步骤
      • 1.导入maven 依赖
        • 2.编写工具类
    1. 导入maven 依赖
    <!-- HttpClinet 核心包 -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
    <!-- HttpClinet 请求时,涉及文件上传需要的包 -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.13</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    1. 工具类代码
    package com.unisoc.releaseCenter.utils;
     
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Objects;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
     
    /**
     * HttpClient工具类
     *
     * @author ZhangYuanqiang
     * @since 2021-06-10
     */
    public class HttpUtils {
     
        /**
         * 字符编码
         */
        private final static String UTF8 = "utf-8";
        /**
         * 字节流数组大小(1MB)
         */
        private final static int BYTE_ARRAY_LENGTH = 1024 * 1024;
     
        /**
         * 执行get请求获取响应
         *
         * @param url 请求地址
         * @return 响应内容
         */
        public static String get(String url) {
            return get(url, null);
        }
     
        /**
         * 执行get请求获取响应
         *
         * @param url     请求地址
         * @param headers 请求头参数
         * @return 响应内容
         */
        public static String get(String url, Map<String, String> headers) {
            HttpGet get = new HttpGet(url);
            return getRespString(get, headers);
        }
     
        /**
         * 执行post请求获取响应
         *
         * @param url 请求地址
         * @return 响应内容
         */
        public static String post(String url) {
            return post(url, null, null);
        }
     
        /**
         * 执行post请求获取响应
         *
         * @param url    请求地址
         * @param params 请求参数
         * @return 响应内容
         */
        public static String post(String url, Map<String, String> params) {
            return post(url, null, params);
        }
     
        /**
         * 执行post请求获取响应
         *
         * @param url     请求地址
         * @param headers 请求头参数
         * @param params  请求参数
         * @return 响应内容
         */
        public static String post(String url, Map<String, String> headers, Map<String, String> params) {
            HttpPost post = new HttpPost(url);
            post.setEntity(getHttpEntity(params));
            return getRespString(post, headers);
        }
     
        /**
         * 执行post请求获取响应(请求体为JOSN数据)
         *
         * @param url  请求地址
         * @param json 请求的JSON数据
         * @return 响应内容
         */
        public static String postJson(String url, String json) {
            return postJson(url, null, json);
        }
     
        /**
         * 执行post请求获取响应(请求体为JOSN数据)
         *
         * @param url     请求地址
         * @param headers 请求头参数
         * @param json    请求的JSON数据
         * @return 响应内容
         */
        public static String postJson(String url, Map<String, String> headers, String json) {
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-type", "application/json");
            post.setEntity(new StringEntity(json, UTF8));
            return getRespString(post, headers);
        }
     
        /**
         * 执行post请求获取响应(请求体包含文件)
         *
         * @param url    请求地址
         * @param params 请求参数(文件对应的value传File对象)
         * @return 响应内容
         */
        public static String postFile(String url, Map<String, Object> params) {
            return postFile(url, null, params);
        }
     
        /**
         * 执行post请求获取响应(请求体包含文件)
         *
         * @param url     请求地址
         * @param headers 请求头参数
         * @param params  请求参数(文件对应的value传File对象)
         * @return 响应内容
         */
        public static String postFile(String url, Map<String, String> headers, Map<String, Object> params) {
            HttpPost post = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if (Objects.nonNull(params) && !params.isEmpty()) {
                for (Entry<String, Object> entry : params.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (Objects.isNull(value)) {
                        builder.addPart(key, new StringBody("", ContentType.TEXT_PLAIN));
                    } else {
                        if (value instanceof File) {
                            builder.addPart(key, new FileBody((File) value));
                        } else {
                            builder.addPart(key, new StringBody(value.toString(), ContentType.TEXT_PLAIN));
                        }
                    }
                }
            }
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            return getRespString(post, headers);
        }
     
        /**
         * 下载文件
         *
         * @param url      下载地址
         * @param path     保存路径(如:D:/images,不传默认当前工程根目录)
         * @param fileName 文件名称(如:hello.jpg)
         */
        public static void download(String url, String path, String fileName) {
            HttpGet get = new HttpGet(url);
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String filePath = null;
            if (Objects.isNull(path) || path.isEmpty()) {
                filePath = fileName;
            } else {
                if (path.endsWith("/")) {
                    filePath = path + fileName;
                } else {
                    filePath += path + "/" + fileName;
                }
            }
            File file = new File(filePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try (FileOutputStream fos = new FileOutputStream(file); InputStream in = getRespInputStream(get, null)) {
                if (Objects.isNull(in)) {
                    return;
                }
                byte[] bytes = new byte[BYTE_ARRAY_LENGTH];
                int len = 0;
                while ((len = in.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        /**
         * 获取请求体HttpEntity
         *
         * @param params 请求参数
         * @return HttpEntity
         */
        private static HttpEntity getHttpEntity(Map<String, String> params) {
            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (Entry<String, String> entry : params.entrySet()) {
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            HttpEntity entity = null;
            try {
                entity = new UrlEncodedFormEntity(pairs, UTF8);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return entity;
        }
     
        /**
         * 设置请求头
         *
         * @param request 请求对象
         * @param headers 请求头参数
         */
        private static void setHeaders(HttpUriRequest request, Map<String, String> headers) {
            if (Objects.nonNull(headers) && !headers.isEmpty()) {
                // 请求头不为空,则设置对应请求头
                for (Entry<String, String> entry : headers.entrySet()) {
                    request.setHeader(entry.getKey(), entry.getValue());
                }
            } else {
                // 请求为空时,设置默认请求头
                request.setHeader("Connection", "keep-alive");
                request.setHeader("Accept-Encoding", "gzip, deflate, br");
                request.setHeader("Accept", "*/*");
                request.setHeader("User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
            }
        }
     
        /**
         * 执行请求,获取响应流
         *
         * @param request 请求对象
         * @return 响应内容
         */
        private static InputStream getRespInputStream(HttpUriRequest request, Map<String, String> headers) {
            // 设置请求头
            setHeaders(request, headers);
            // 获取响应对象
            HttpResponse response = null;
            try {
                response = HttpClients.createDefault().execute(request);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            // 获取Entity对象
            HttpEntity entity = response.getEntity();
            // 获取响应信息流
            InputStream in = null;
            if (Objects.nonNull(entity)) {
                try {
                    in = entity.getContent();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return in;
        }
     
        /**
         * 执行请求,获取响应内容
         *
         * @param request 请求对象
         * @return 响应内容
         */
        private static String getRespString(HttpUriRequest request, Map<String, String> headers) {
            byte[] bytes = new byte[BYTE_ARRAY_LENGTH];
            int len = 0;
            try (InputStream in = getRespInputStream(request, headers);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                if (Objects.isNull(in)) {
                    return "";
                }
                while ((len = in.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                return bos.toString(UTF8);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
     
    }
    
    • 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
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
  • 相关阅读:
    Oracle的控制文件多路复用,控制文件备份,控制文件手工恢复
    Android简易音乐重构MVVM Java版-使用DiffUtil解决recycleView整体数据刷新性能问题(二十二)
    C++学习记录1
    USB 2.0 10/100M Ethernet Adaptor 有线网卡驱动
    JAVA茶叶销售网站计算机毕业设计Mybatis+系统+数据库+调试部署
    基于STM32的智能GPS定位系统(云平台、小程序)
    前端全局工具函数utils.js/正则(持续更新)
    家用厨房电器测试报告办理流程
    Ubuntu22.04本地部署PaddleSpeech实验代码(GPU版)
    30个Python常用极简代码,拿走就用
  • 原文地址:https://blog.csdn.net/qq_33240556/article/details/132965710