在 Java 中,URL 中不能直接包含中文字符,因?yàn)?URL 規(guī)范要求 URL 必須是 ASCII 字符。如果需要在 URL 中傳遞中文參數(shù),需要對(duì)中文參數(shù)進(jìn)行 URL 編碼,將其轉(zhuǎn)換為瀏覽器中的參數(shù)形式??梢允褂?java.net.URLEncoder
類來進(jìn)行 URL 編碼。文章來源地址http://www.zghlxwxcb.cn/news/detail-669718.html
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 請(qǐng)求的 URL
String baseUrl = "https://jsonplaceholder.typicode.com/posts";
// 構(gòu)建參數(shù)字符串,例如:?param1=value1¶m2=value2
String param1 = "中文參數(shù)1";
String param2 = "中文參數(shù)2";
//一個(gè)參數(shù)傳參的示例(keyWord是參數(shù))
String parameters = String.format("%s", URLEncoder.encode(keyWord, "UTF-8"));
String parameters = String.format("param1=%s¶m2=%s", URLEncoder.encode(param1, "UTF-8"), URLEncoder.encode(param2, "UTF-8"));
// 創(chuàng)建 URL 對(duì)象
URL obj = new URL(baseUrl + "?" + parameters);
// 打開連接
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
// 設(shè)置請(qǐng)求方法為 GET
conn.setRequestMethod("GET");
// 發(fā)送 GET 請(qǐng)求并獲取響應(yīng)
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();
}
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-669718.html
到了這里,關(guān)于Java 發(fā)送Http請(qǐng)求攜帶中文參數(shù)時(shí) 請(qǐng)求報(bào)400的錯(cuò)誤請(qǐng)求的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!