HttpGet中的android java.lang.IllegalArgumentException

kon*_*ger 5 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; 
    }
Run Code Online (Sandbox Code Playgroud)

而且我得到了以下异常HttpGet httpGet = new HttpGet(url):

java.lang.IllegalArgumentException异常:在索引59中的查询非法字符http://www.pappico.ru/promo.php?action=RegisterUserms= { "用户id":1, "username"的: "ЮрийКлинских"}

'{'字符有什么问题?我已经阅读了一些关于此异常的帖子并找到了一个解决方案,但是这个解决方案会导致另一个异常:如果我解开了行,url = URLEncoder.encode(url, "UTF-8");它就会response = httpClient.execute(httpGet);出现这样的异常:

java.lang.IllegalStateException:目标主机不能为null,或者在参数中设置.方案= NULL,主机= NULL,路径= http://www.pappico.ru/promo.php?action=RegisterUserms= { "用户id":1, "userName的": "+ЮрийКлинских"}

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

jdb*_*jdb 7

您必须对URL参数进行编码:

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

  • 在我看来,这是我的错 - 我正在使用UI线程中的网络)) (3认同)