Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android java.lang.IllegalArgumentException in HttpGet [duplicate]

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:)

like image 669
konunger Avatar asked Mar 07 '13 00:03

konunger


1 Answers

You have to encode the URL parameters:

String request = baseRequestUrl + "RegisterUser&params=" +    
        java.net.URLEncoder.encode("{\"userId\":" + userId + ",\"userName\":\"" + userName + "\"}", "UTF-8");
like image 50
jdb Avatar answered Nov 06 '22 09:11

jdb