java - HttpGet 中的 android java.lang.IllegalArgumentException

标签 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: Illegal character in query at index 59: http://www.pappico.ru/promo.php?action=RegisterUser&params={"userId":1,"userName":"Юрий Клинских"}

'{' 字符有什么问题?我已经阅读了一些关于此异常的帖子并找到了解决方案,但此解决方案会导致另一个异常:如果我取消注释行 url = URLEncoder.encode(url, "UTF-8"); 它会在行中崩溃response = httpClient.execute(httpGet); 有这样的异常(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":"Юрий+Клинских"}

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

最佳答案

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

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

关于java - HttpGet 中的 android java.lang.IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15260718/

相关文章:

java - 重复发送 HTTP 请求,即使应用程序在 Android 上处于后台时也是如此

java - jMeter 在扫描仪读取时挂起

android - room db 使用@query 更新多行

android - 生命周期 Android 插件 gradle

Android HTTP 获取

c# - 如何处理传输编码 : chunked when downloading a file with . NET Core HttpClient.PostAsync

java - Android:在外部存储上写入/读取文件时出现问题

java - 在 Jersey 中将 int 数组作为 @QueryParam 发送

java - 使用 ExifInterface 时出现 FileNotFoundException

java - 如何使用 native Java 库修复多个已弃用的 Http* 类和方法