解决HttpClient工具中application/x-www-form-urlencoded表单提交时,请求参数中文乱码问题

一、参数乱码现象

当我去请求第三方接口时,接口接收格式为Form表单的时候,使用HttpClient工具类。这时,对于封装进HttpPost对象里的请求参数,如果有中文参数,会出现乱码的现象。

二、代码现象复现

controller层
@RestController
@RequestMapping(value = "/http")
public class HttpClientController {

    @GetMapping(value = "/get")
    public PrePayResultVO getHttpClientDemo() {

        String url = "https://xxxx.xxxx.com/xxxx/Xxxxx";
        Map map = new HashMap<>();
        map.put("cardId", "1234567890");
        map.put("carNumber", "粤LX255Q");
        map.put("parkCode", "1234567890");
        map.put("startTime", "2018-09-18");
        map.put("endTime", "2018-10-18");
        map.put("defferMoney", "0.01");

        JSONObject jsonObject = HttpClientUtils.postForForm(url, map);
        PrePayResultVO prePayResultVO =JSONObject.parseObject(jsonObject.toString(), PrePayResultVO.class);
        return prePayResultVO;
    }
}
httpClientUtils
public static JSONObject postForForm(String url, Map<String, String> parms) {
        HttpPost httpPost = new HttpPost(url);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (Objects.nonNull(parms) && parms.size() >0) {
                httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            InputStream content = httpPost.getEntity().getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String readLine = bufferedReader.readLine();
            System.out.println("readLine===================================" + readLine);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
            return jsonObject;
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(httpClient)){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
打印结果

中文乱码
由此可见,本应打印中的请求参数 “粤LX255Q”,却变成了 “%E7%B2%A4LX255Q” 这种格式的字符串。

三、产生原因

在我们发起请求时,浏览器首先会将这些中文字符进行编码然后再发送给服务器。实际上,浏览器会将它们转换为 application/x-www-form-urlencoded MIME 字符串。

四、解决方法

 public static JSONObject postForForm(String url, Map<String, String> parms) {
        HttpPost httpPost = new HttpPost(url);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (Objects.nonNull(parms) && parms.size() >0) {
                httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            InputStream content = httpPost.getEntity().getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String readLine = bufferedReader.readLine();
            String s = URLDecoder.decode(readLine, "UTF-8");
            System.out.println("readLine===================================" + readLine);
            System.out.println("s==========================================" + s);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
            return jsonObject;
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(httpClient)){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

在获取请求参数时,再对其使用URLDecoder将application/x-www-form-rulencoded MIME字符串转换为对应编码的普通字符串。

打印结果

解决方法

五、URLDecoder和URLEncoder的使用总结

  • URLDecoder类包含一个decode(String s,String enc)静态方法,它可以将application/x-www-form-urlencoded MIME字符串转成普通字符串;

  • URLEncoder类包含一个encode(String s,String enc)静态方法,它可以将普通字符串转换成application/x-www-form-urlencoded MIME字符串。

public static void main(String[] args) throws UnsupportedEncodingException {
        String name = "千夜";

        String decode = URLDecoder.decode("%E5%8D%83%E5%A4%9C", "UTF-8");
        System.out.println("application/x-www-form-urlencoded MIME字符串转成普通字符串===============" + decode);
        String encode = URLEncoder.encode(name, "UTF-8");
        System.out.println("普通字符串转换成application/x-www-form-urlencoded MIME字符串=============" +encode);
    }
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你可以使用Java的HttpURLConnection类来发送POST请求。以下是一个简的示例: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { private final String USER_AGENT = "Mozilla/5.0"; public static void main(String[] args) throws Exception { PostRequestExample http = new PostRequestExample(); // POST请求URL String url = "http://111.203.10.155/MicroApp/nmsmc-system-basic/dict"; // POST请求参数 String urlParameters = "param1=value1&param2=value2"; // 发送POST请求 String response = http.sendPost(url, urlParameters); System.out.println(response); } // 发送POST请求 private String sendPost(String url, String urlParameters) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 添加请求头 con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // 发送POST请求 con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // 读取响应内容 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } } ``` 在上面的示例,我们通过设置请求方法为“POST”,添加请求头和发送POST请求参数来发送POST请求。在响应,我们使用BufferedReader读取响应内容。你需要将示例的URL和请求参数替换为你自己的URL和请求参数。 ### 回答2: 在Java使用POST请求访问http://111.203.10.155/MicroApp/nmsmc-system-basic/dict的步骤如下: 1. 创建一个URL对象,将要访问的地址传递给URL构造函数。 ```java URL url = new URL("http://111.203.10.155/MicroApp/nmsmc-system-basic/dict"); ``` 2. 创建一个HttpURLConnection对象,通过调用URL对象的openConnection方法。 ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); ``` 3. 设置请求方法为POST。 ```java connection.setRequestMethod("POST"); ``` 4. 设置请求头的内容类型。 ```java connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); ``` 5. 开启输出流,准备发送请求体。 ```java connection.setDoOutput(true); ``` 6. 准备请求参数,并将其写入输出流。 ```java String parameters = "key1=value1&key2=value2"; OutputStream outputStream = connection.getOutputStream(); outputStream.write(parameters.getBytes()); outputStream.flush(); outputStream.close(); ``` 7. 发送请求并获取响应码。 ```java int responseCode = connection.getResponseCode(); ``` 8. 判断响应码是否为200,请求成功。 ```java if (responseCode == 200) { // 请求成功,获取响应数据 InputStream inputStream = connection.getInputStream(); // 处理响应数据 inputStream.close(); } ``` 需要注意的是,除了以上步骤,如果服务器要求进行身份验证,还需要添加相应的认证信息,比如用户名和密码。另外,在实际应用可能会遇到更多的异常情况,需要进行适当的异常处理。以上步骤只是基本的POST请求流程,具体的实现还需要根据实际情况进行调整。 ### 回答3: 在Java程序使用Post请求访问"http://111.203.10.155/MicroApp/nmsmc-system-basic/dict",可以通过使用Java提供的HttpClient库来实现。 首先,我们需要引入HttpClient库的依赖。在构建工具如Maven或Gradle,可以添加以下依赖: Maven: ```xml <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> </dependencies> ``` Gradle: ```groovy dependencies { implementation 'org.apache.httpcomponents:httpclient:4.5.13' } ``` 然后,可以通过以下代码片段使用Post请求访问目标URL: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; public class PostExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://111.203.10.155/MicroApp/nmsmc-system-basic/dict"); // 设置请求参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("key1", "value1")); params.add(new BasicNameValuePair("key2", "value2")); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // 处理响应结果 if (httpEntity != null) { String responseString = EntityUtils.toString(httpEntity, "UTF-8"); System.out.println(responseString); } } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码示例创建一个HttpPost对象,并通过setEntity方法设置请求参数。然后使用HttpClient的execute方法发送请求并获取响应。最后,可以通过解析响应实体的内容,使用EntityUtils将其转换为字符串并进行处理。 当然,具体的请求参数和响应结果处理需要根据目标URL的要求进行调整,以上代码仅提供了一个Post请求案例的基本骨架。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值