HttpGet中的android java.lang.IllegalArgumentException

时间:2013-03-07 00:09:58

标签: java android httpclient

我正试图从远程服务器获得响应。这是我的代码:

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; 
    }

我在第HttpGet httpGet = new HttpGet(url)行中遇到以下异常:

  

java.lang.IllegalArgumentException:索引59处查询中的非法字符:http://www.pappico.ru/promo.php?action=RegisterUser&params= {“userId”:1,“userName”:“ЮрийКлинских”}

'{'字符有什么问题?我已经阅读了一些关于此异常的帖子并找到了解决方案,但此解决方案会导致另一个例外:如果我取消注释行url = URLEncoder.encode(url, "UTF-8");,它会在行response = httpClient.execute(httpGet);处崩溃,但有以下异常:

  

java.lang.IllegalStateException:目标主机不能为null,或者在参数中设置。 scheme = null,host = null,path = http://www.pappico.ru/promo.php?action=RegisterUser&params= {“userId”:1,“userName”:“Юрий+Клинских”}

不知道我该怎么做才能让它发挥作用。任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:7)

您必须对网址参数进行编码:

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

答案 1 :(得分:0)

尝试:

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;
    }

(这对params = ...中的URL片段进行编码),而不是整个URL。您还可以查看上面提到的duplicate


加成: 请注意,JSON通常通过POST(而不是GET)传输。您可以使用“Live Headers”之类的程序并手动执行这些步骤(例如注册用户)以查看幕后发生的情况。在这种情况下,您将在实体主体中发送{..}信息。这是一种方法 - HTTP POST using JSON in Java

另外,另一种编写JSON的方法(特别是当它变得更复杂时)是使用模型类,然后使用ObjectMapper(例如Jackson)将其转换为字符串。这很方便,因为你避免在你的字符串中使用像\“这样的格式。

以下是一些例子:JSON to Java Objects, best practice for modeling the json stream