HttpPost使用setEntity传递参数传了个寂寞

不知道为啥下面两种方式都无法获取参数值。
指定Content-Type为application/json,发送json数据。
方法1

httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setEntity(new StringEntity(params.toJSONString(), StandardCharsets.UTF_8));

方法2

httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
List<NameValuePair> paramsList = new ArrayList<>();
params.forEach((key, value) -> {
	paramsList.add(new BasicNameValuePair(key, (String) value));
});
httpPost.setEntity(new UrlEncodedFormEntity(paramsList, StandardCharsets.UTF_8));

后来试了一下 指定Content-Type为application/x-www-form-urlencoded,发送用&连接的数据,接口用实际参数名接收,这样可以拿到参数值。

StringBuilder paramsStr = new StringBuilder();
params.forEach((key, value) -> {
	try {
    	paramsStr.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(value), "UTF-8")).append("&");
    } catch (UnsupportedEncodingException e) {
    	e.printStackTrace();
    }
});


httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setEntity(new StringEntity(paramsStr.substring(0, paramsStr.length() - 1), StandardCharsets.UTF_8));

下面是一个http请求的通用类。

package com.ieslab.wechatapi;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: Http请求工具类
 * @author: yiwenli
 * @create: 2021-04-08 09:32
 **/
public class HttpRequestUtil {

    public static void main(String[] args) throws IOException {
        String url = "http://localhost:8000/wechatApp/powerBalance/getPowerGenerationCurveData";
        JSONObject paramMap = new JSONObject();
        paramMap.put("date", "2021-03-08");
//        String result = httpRequest(url, "GET", paramMap);
        String result = httpRequest(url, "POST", paramMap);
        JSONObject resultObject = JSONObject.parseObject(result);
        System.out.println(11);
    }

	/**
     * 发送http请求
     * 
     * @param requestUrl    请求地址
     * @param params        请求参数
     * @param requestMethod 请求方式  POST/GET
     */
    public static String httpRequest(String requestUrl, JSONObject params, String requestMethod) {
        String result = null;
        StringBuilder paramsStr = new StringBuilder();
        params.forEach((key, value) -> {
            try {
                paramsStr.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(value), "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        });
        if("POST".equals(requestMethod)) {

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(30 * 1000)
                    .setConnectTimeout(30 * 1000)
                    .setConnectionRequestTimeout(30 * 1000)
                    .build();
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new StringEntity(paramsStr.substring(0, paramsStr.length() - 1), StandardCharsets.UTF_8));
            
            try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
                 CloseableHttpResponse response = httpclient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else if("GET".equals(requestMethod)) {

            String requestUrlWithParam = requestUrl + "?" + paramsStr.substring(0, paramsStr.length() - 1);
            HttpGet httpGet = new HttpGet(requestUrlWithParam);
            try(CloseableHttpClient httpClient = HttpClients.createDefault();
                CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
                HttpEntity httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return result;
    }

}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值