我正在测试下面的代码以发送带有参数的 GET 请求,当参数的值是包含空格的字符串时,此代码会失败,例如:http://company.com/example.php?value=Jhon 123。如果我发送Jhon123(没有任何空格)就可以正常工作了。
为什么会出现这种情况?
private static void sendGet(String site, String params) throws Exception {
site += params;
URL obj = new URL(site);
try {
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + site);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
} catch (Exception ex) {
}
}
Run Code Online (Sandbox Code Playgroud)