java – 这个URI URL有什么问题? IllegalArgumentException,非法字符

我收到一个错误:

W/System.err(32720): java.lang.IllegalArgumentException: Illegal character in query at index 89: https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f={%20mean0%22:%201}&apiKey=myApiKey


String apiURI = "https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f={%22mean0%22:%201}&apiKey=myApiKey";

>当我将此URI粘贴到浏览器中时,它可以正常工作.
>当我粘贴到浏览器中,打开它,然后将URI复制回我的代码,它没有帮助.
>指数89是{ – 这是一个非法的人物?

我尝试这样做 – 用{代替大括号,但它没有帮助

https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f=%7B"mean0":%201%7D&apiKey=myApiKey

任何人?

编辑:

    String query = "https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f={\""+arrayName+"\":%201}&apiKey=myApiKey";
    try {
        query = URLEncoder.encode(query, "utf-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String apiURI = query;

没有帮助.现在我得到:

05-23 22:13:21.855: E/SendMail(12428): Target host must not be null, or set in parameters. scheme=null, host=null, path=https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f={"mean0":%201}&apiKey=myAPI

如果我在查询声明中更改为空格,那么我得到:

 05-23 22:14:51.435: E/SendMail(13164): Target host must not be null, or set in parameters. scheme=null, host=null, path=https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f={"mean0":+1}&apiKey=myAPI

另外如果我不在中间使用arrayName字符串,只是直接从浏览器使用字符串,效果是一样的!

最佳答案 从我所看到的,每次尝试都会错过某些东西,编码不应该的东西,例如’?’,或者对某些东西进行双重编码,从而对url编码中的’%’进行url编码.

如何只是编码你关心转义的位,并完成一次?

String apiURI =
    "https://api.mongolab.com/api/1/databases/activity_recognition/collections/entropy_data?f="
    + URLEncoder.encode("{\"mean0\": 1}", "UTF-8")
    + "&apiKey=myApiKey";

如果你想使用java.net.URI,你必须单独包含查询字符串,例如:

new URI(
    "https",
    "api.mongolab.com",
    "/api/1/databases/activity_recognition/collections/entropy_data",
    "f={\"mean0\": 1}&apiKey=myApiKey",
    null
  ).toURL()
点赞