如何使用包含空格的参数值发送GET请求?

时间:2017-11-09 02:23:17

标签: java http get-request

我正在测试下面的代码,用参数发送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) {
        }

    }

2 个答案:

答案 0 :(得分:2)

您应该URL Encode您的请求。

答案 1 :(得分:0)

您可以使用URLEncoder对参数进行编码:

String url = "http://company.com/example.php?value=" + URLEncoder.encode("Jhon 123", "utf-8");