4

我收到一个错误:

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 是 { - 这怎么是非法字符?

我试过这样做 - 用 %7B: 替换大括号:但这没有帮助

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

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

 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字符串而直接使用浏览器中的字符串,效果是一样的!

4

3 回答 3

5

从我所见,每次尝试要么错过某些东西,编码不应该的东西,例如'?',要么双重编码某些东西,从而在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()
于 2013-05-23T22:40:54.917 回答
-1

另一种方法是:

uri = new URI("https", 
"api.mongolab.com", 
"/api/1/databases/activity_recognition/collections/entropy_data?f={\"mean\": 1}&apiKey=myApiKey", null);
URL url = uri.toURL();

请注意,我将 %22 (urlencoded 引号)更改为 \" (转义引号),否则您最终会看到 % 符号被 urlencoded。

为了澄清,这一点是,如果你这样做:

String query = "https://api.mongolab.com...";
query = URLEncoder.encode(query, "utf-8");

你最终会得到 https%3A%2F%2Fapi.mongolab.com。

于 2013-05-23T21:24:28.183 回答
-2

我猜你正在寻找这样的东西

String flag1 = URLEncoder.encode("This string has spaces", "UTF-8");

您可以参考Oracle URL Encoder的文档或参考SOF

于 2013-05-23T21:11:54.890 回答