java --封装一个postByForm请求

该代码段展示了如何在Java中使用HttpClient库进行POST请求,包括设置URL、请求参数、字符编码以及自定义headers。它创建了HttpPost对象,处理参数列表,并将响应转换为字符串。
摘要由CSDN通过智能技术生成

很多时候请求也有head等附加参数的时候,封装了一个使用

   /**
     * post
     * @param url
     * @param map
     * @param charset
     * @param headers
     * @return
     */
    public static String postByForm(String url, Map<String, String> map,String charset,Map<String, String> headers){
        HttpClient httpClient = HttpClientBuilder.create().build();
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置头部
            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
            if(headers != null) {
                Iterator headersIterator = headers.entrySet().iterator();
                while (headersIterator.hasNext()) {
                    Map.Entry<String, String> elem = (Map.Entry<String, String>) headersIterator.next();
                    httpPost.addHeader(elem.getKey(), elem.getValue());
                }
            }
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            log.error("网络请求异常:{}",ex);
        }
        return result;

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值