What is wrong with this URI URL? IllegalArgumentException, Illegal character What is wrong with this URI URL? IllegalArgumentException, Illegal character mongodb mongodb

What is wrong with this URI URL? IllegalArgumentException, Illegal character


From what I've seen, every attempt either misses something, encodes something it shouldn't, such as the '?', or double-encodes something, thereby url-encoding the '%' in the url encoding.

How about just encoding the bit you care about escaping, and doing it exactly once?

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

If you wanted to use java.net.URI, you'd have to include the query string separately, e.g.:

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


Another way to do this would be:

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();

Note that I changed the %22 (urlencoded quotes) to \" (escaped quotes) otherwise you will wind up with your % sign being urlencoded.

To clarify, the point of this is that if you do this:

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

you will wind up with https%3A%2F%2Fapi.mongolab.com.


I guess you are looking for something like this

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

You can refer to the documentation from Oracle URL Encoder or refer to SOF