Java 发送Http请求携带中文参数时 请求报400的错误请求

该代码示例展示了如何在Java中使用URLEncoder对中文参数进行URL编码,以便在GET请求的URL中安全传递。通过指定URL,对每个中文参数进行UTF-8编码,然后构造带参数的URL,最终发送HTTPGET请求并读取响应。

在 Java 中,URL 中不能直接包含中文字符,因为 URL 规范要求 URL 必须是 ASCII 字符。如果需要在 URL 中传递中文参数,需要对中文参数进行 URL 编码,将其转换为浏览器中的参数形式。可以使用 java.net.URLEncoder 类来进行 URL 编码。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpGetWithEncodedChineseParametersExample {

    public static void main(String[] args) {
        try {
            // 指定 GET 请求的 URL
            String baseUrl = "https://jsonplaceholder.typicode.com/posts";
            // 构建参数字符串,例如:?param1=value1&param2=value2
            String param1 = "中文参数1";
            String param2 = "中文参数2";
            //一个参数传参的示例(keyWord是参数)
            String parameters = String.format("%s", URLEncoder.encode(keyWord, "UTF-8"));
            String parameters = String.format("param1=%s&param2=%s", URLEncoder.encode(param1, "UTF-8"), URLEncoder.encode(param2, "UTF-8"));

            // 创建 URL 对象
            URL obj = new URL(baseUrl + "?" + parameters);
            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            // 设置请求方法为 GET
            conn.setRequestMethod("GET");

            // 发送 GET 请求并获取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println("GET Response: " + response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值