5

I'm trying to get response from remote server. Here is my code:

private static String baseRequestUrl = "http://www.pappico.ru/promo.php?action=";

    @SuppressWarnings("deprecation")
    public String executeRequest(String url) {
        String res = "";
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response;      

        try {   
            //url = URLEncoder.encode(url, "UTF-8");
            HttpGet httpGet = new HttpGet(url);

            response = httpClient.execute(httpGet);
            Log.d("MAPOFRUSSIA", response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inStream = entity.getContent();
                res = streamToString(inStream);

                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res; 
    }

    public String registerUser(int userId, String userName) {
        String res = "";
        String request = baseRequestUrl + "RegisterUser&params={\"userId\":" +
                 userId + ",\"userName\":\"" + userName + "\"}";

        res = executeRequest(request);

        return res; 
    }

And I'm getting the following exception in line HttpGet httpGet = new HttpGet(url):

java.lang.IllegalArgumentException: Illegal character in query at index 59: http://www.pappico.ru/promo.php?action=RegisterUser&params={"userId":1,"userName":"Юрий Клинских"}

What's wrong with '{' character? I already read some posts about this exception and found a solution, but this solution causes another exception: if I uncommet line url = URLEncoder.encode(url, "UTF-8"); it craches at line response = httpClient.execute(httpGet); with such exception:

java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://www.pappico.ru/promo.php?action=RegisterUser&params={"userId":1,"userName":"Юрий+Клинских"}

Don't know what should I do to make it work. Any help would be appreciated:)

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
konunger
  • 186
  • 3
  • 14

2 Answers2

7

You have to encode the URL parameters:

String request = baseRequestUrl + "RegisterUser&params=" +    
        java.net.URLEncoder.encode("{\"userId\":" + userId + ",\"userName\":\"" + userName + "\"}", "UTF-8");
jdb
  • 4,419
  • 21
  • 21
0

Try:

public String registerUser(int userId, String userName) {
        String res = "";

        String json = "{\"userId\":" +
                 userId + ",\"userName\":\"" + userName + "\"}";
        String encodedJson = URLEncoder.encode(json, "utf-8");

        String request = baseRequestUrl + "RegisterUser&params=" + encodedJson;

        res = executeRequest(request);
        return res;
    }

(This encodes the URL fragment in params=...), rather than the whole URL. You might also take a look at the possible duplicate mentioned above.


Bonus: Note that JSON is typically transferred via POST (instead of a GET). You can use a program like "Live Headers" and do the steps manually (e.g. register a user) to see what's going on behind the scenes. In this case, you'd be sending the {..} info in the entity body. Here's one way to do that - HTTP POST using JSON in Java

Also, another approach to writing JSON (especially when it gets more complicated) is to use a model class and then an ObjectMapper (such as Jackson) to convert it to a string. This is handy because you avoid having formatting like \" in your strings.

Here's some examples of that: JSON to Java Objects, best practice for modeling the json stream

Community
  • 1
  • 1
Pancakeo
  • 1,846
  • 1
  • 12
  • 5