3

I'm testing this code below to send GET request with parameters and this code fails when the value of parameter is a string containing a space, Ex: http://company.com/example.php?value=Jhon 123. Already if i send Jhon123 (withou any space) works fine.

Why this happens?

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

    }
user207421
  • 305,947
  • 44
  • 307
  • 483
  • you can use a lot of encode decode method on queryString, urlencode is the easiest which follow browser standard but may some times fail, base64 is a better approach if you data is not too large in scale – PSo Nov 09 '17 at 02:42
  • 1
    @PSo, thank you. `URLEncoder` was the solution to this my trouble. –  Nov 09 '17 at 03:23

2 Answers2

5

You should URL Encode your request.

rai
  • 449
  • 3
  • 10
3

You can use URLEncoder to encode your parameter:

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