如何发送参数值包含 space 的 GET 请求?

How send GET request with value of parameter containing a space?

我正在测试下面的代码以发送带参数的 GET 请求,当参数值是包含 space 的字符串时,此代码失败,例如:http://company.com/example.php?value=Jhon 123。如果我发送 Jhon123(没有任何 space)就可以正常工作。

为什么会这样?

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) {
        }

    }

你应该URL Encode你的要求。

您可以使用URLEncoder来编码您的参数:

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