• Java使用x-www-form-urlencoded发请求


    平常在开发过程中用的最多的就是JSON格式,请求编码就是 application/json,但偏偏有些接口是 x-www-form-urlencoded,怎么办呢,重新封装喽
    在POSTMan工具是叫 x-www-form-urlencoded
    在 APIpost工具中是叫 urlencoded
    在这里插入图片描述

    Map<String, String> request = new HashMap<>();
            request.put("username", "xxx");
            request.put("password", "xxx");
            String result = HttpRequestUtil.post(request, "http://xxxx", new HashMap<String, String>(), "application/x-www-form-urlencoded");
            System.out.println(result);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    package utils;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.HttpStatus;
    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.HttpDelete;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.message.BasicNameValuePair;
    
    import com.alibaba.fastjson.JSONObject;
    
    
    
    
    /**
     *    
     * @ClassName:HttpRequestUtil   
     * @Description: Http请求  
     */
    public class HttpRequestUtil {
        private String defaultContentEncoding;
     
        public HttpRequestUtil() {
            this.defaultContentEncoding = Charset.defaultCharset().name();
        }
        
        /**
         * 默认的响应字符集
         */
        public String getDefaultContentEncoding() {
            return this.defaultContentEncoding;
        }
     
        /**
         * 设置默认的响应字符集
         */
        public void setDefaultContentEncoding(String defaultContentEncoding) {
            this.defaultContentEncoding = defaultContentEncoding;
        }
        
        public static String post(JSONObject json, String url) throws Exception{
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                StringEntity s = new StringEntity(json.toString(),"utf-8");
                s.setContentEncoding("UTF-8");
                /*发送json数据需要设置contentType*/
                s.setContentType("application/json");
                post.setEntity(s);
                post.setHeader("Content-Type","application/json;charset=utf-8");
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
               // System.out.println("返回数据="+result);
            } catch (Exception e) {
                //System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                if(null != br) br.close();
                if(null != br) in.close();
                if(null != response) response.close();
                if(null != httpclient) httpclient.close();
            }
            return result;
        }
        
        public static String post(JSONObject json, String url, Map<String, String> headerMap) throws Exception{
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                StringEntity s = new StringEntity(json.toString(),"utf-8");
                s.setContentEncoding("UTF-8");
                /*发送json数据需要设置contentType*/
                s.setContentType("application/json");
                post.setEntity(s);
                post.setHeader("Content-Type","application/json;charset=utf-8");
                Set<Entry<String, String>> headerEntries = headerMap.entrySet();
                for (Entry<String, String> headerEntry:headerEntries){
                    post.setHeader(headerEntry.getKey(), headerEntry.getValue());
                }
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
                //System.out.println("返回数据="+result);
            } catch (Exception e) {
                //System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                br.close();
                in.close();
                response.close();
                httpclient.close();
            }
            return result;
        }
        
        /**
         * ContentType.URLENCODED.getHeader()
         * @param map
         * @param url
         * @param headerMap
         * @param contentType
         * @return
         * @throws Exception
         */
        public static String post(Map<String, String> map, String url, Map<String, String> headerMap, String contentType) throws Exception{
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                List<NameValuePair> nameValuePairs = getNameValuePairList(map);
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
                /*发送json数据需要设置contentType*/
                urlEncodedFormEntity.setContentType(contentType);
                post.setEntity(urlEncodedFormEntity);
                post.setHeader("Content-Type", contentType);
                Set<Entry<String, String>> headerEntries = headerMap.entrySet();
                for (Entry<String, String> headerEntry:headerEntries){
                    post.setHeader(headerEntry.getKey(), headerEntry.getValue());
                }
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
                //System.out.println("返回数据="+result);
            } catch (Exception e) {
                //System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                br.close();
                in.close();
                response.close();
                httpclient.close();
            }
            return result;
        }
        
        private static List<NameValuePair> getNameValuePairList(Map<String, String> map) {
            List<NameValuePair> list = new ArrayList<>();
            for(String key : map.keySet()) {
                list.add(new BasicNameValuePair(key,map.get(key)));
            }
            
            return list;
        }
    
        public static String post(String params, String url, Map<String, String> headerMap) throws Exception{
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                StringEntity s = new StringEntity(params.toString(),"utf-8");
                s.setContentEncoding("UTF-8");
                /*发送json数据需要设置contentType*/
                s.setContentType("application/json");
                post.setEntity(s);
                post.setHeader("Content-Type","application/json;charset=utf-8");
                Set<Entry<String, String>> headerEntries = headerMap.entrySet();
                for (Entry<String, String> headerEntry:headerEntries){
                    post.setHeader(headerEntry.getKey(), headerEntry.getValue());
                }
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
                //System.out.println("返回数据="+result);
            } catch (Exception e) {
                //System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                br.close();
                in.close();
                response.close();
                httpclient.close();
            }
            return result;
        }
    
        public static String put(JSONObject json, String url, Map<String, String> headerMap) throws Exception {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPut post = new HttpPut(url);
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                StringEntity s = new StringEntity(json.toString(),"utf-8");
                s.setContentEncoding("UTF-8");
                /*发送json数据需要设置contentType*/
                s.setContentType("application/json");
                post.setEntity(s);
                post.setHeader("Content-Type","application/json;charset=utf-8");
                Set<Entry<String, String>> headerEntries = headerMap.entrySet();
                for (Entry<String, String> headerEntry:headerEntries){
                    post.setHeader(headerEntry.getKey(), headerEntry.getValue());
                }
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
                //System.out.println("返回数据="+result);
            } catch (Exception e) {
                //System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                br.close();
                in.close();
                response.close();
                httpclient.close();
            }
            return result;
        }
    
        public static String delete(String url, Map<String, String> headerMap) throws Exception {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpDelete post = new HttpDelete(url);
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                post.setHeader("Content-Type","application/json;charset=utf-8");
                Set<Entry<String, String>> headerEntries = headerMap.entrySet();
                for (Entry<String, String> headerEntry:headerEntries){
                    post.setHeader(headerEntry.getKey(), headerEntry.getValue());
                }
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
                //System.out.println("返回数据="+result);
            } catch (Exception e) {
                //System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                br.close();
                in.close();
                response.close();
                httpclient.close();
            }
            return result;
        }
    
        public static String get(JSONObject paramsObj, String url, Map<String, String> headerMap) throws Exception {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            CloseableHttpResponse  response = null;
            InputStream in = null;
            BufferedReader br = null;
            String result = "";
            try {
                StringBuffer param = new StringBuffer();
                int i = 0;
                
                Set<Entry<String, Object>> entries = paramsObj.entrySet();
                for (Entry<String, Object> entry:entries){
                    if (i == 0)
                        param.append("?");
                    else
                        param.append("&");
                    param.append(entry.getKey()).append("=").append(entry.getValue());
                    i++;
                }
                
                url += param;
                HttpGet post = new HttpGet(url);
    //            post.setHeader("Content-Type","application/json;charset=utf-8");
                
                Set<Entry<String, String>> headerEntries = headerMap.entrySet();
                for (Entry<String, String> headerEntry:headerEntries){
                    post.setHeader(headerEntry.getKey(), headerEntry.getValue());
                }
                
                response = httpclient.execute(post);
                in = response.getEntity().getContent();
                br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                StringBuilder strber= new StringBuilder();
                String line = null;
                while((line = br.readLine())!=null){
                    strber.append(line+'\n');
                }
                result = strber.toString();
                if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
                    if(StringUtils.isBlank(result)) result = "服务器异常";
                    throw new Exception(result);
                }
                //System.out.println("返回数据="+result);
            } catch (Exception e) {
               // System.err.println("调用接口出错::::::::::::"+e.getMessage());
                throw new Exception(e.getMessage());
            } finally {
                br.close();
                in.close();
                response.close();
                httpclient.close();
            }
            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
    • 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
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
  • 相关阅读:
    这几个拍图读字软件你见过吗?附赠使用方法
    猿创征文|最长回文子串-力扣
    Nacos注册中心8-Server端(处理注册请求)
    2024年,如何使用chatgpt4.0为工作赋能?
    hadoop生态圈之hive面试(一)
    学习爬虫之Scrapy框架学习(1)---Scrapy框架初学习及豆瓣top250电影信息获取的实战!
    《深入浅出消息中间件》-RabbitMQ 安装
    React【axios、全局处理、 antd UI库、更改主题、使用css module的情况下修改第三方库的样式、支持sass & less】(十三)
    Java版本企业工程项目管理系统平台源码(三控:进度组织、质量安全、预算资金成本、二平台:招采、设计管理)
    vue使用scope插槽实现dialog窗口
  • 原文地址:https://blog.csdn.net/lhg_55/article/details/123297389