1

I'm using Apache HttpClient v4.2.2 to try and hit a URL, and am getting a URISyntaxException that I can't seem to figure out:

try {
    String uri = "http://a.example.com/12/allrigh/bouncer?my_key1=i[(Gz$xrCcCeaCrHv}[5Ryou4kz@Yh~c@K_if-p7vGQ3ZF[fEpm2SmH(Z6Yh40Ea";

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(uri);
    HttpResponse response = httpClient.execute(httpGet);
} catch(Throwable throwable) {
    // Log & handle
}

Exception in thread "main" java.lang.IllegalArgumentException
    at java.net.URI.create(URI.java:859)
    at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
    ...
Caused by: java.net.URISyntaxException: Illegal character in query at index 65: http://a.example.com/12/allrigh/bouncer?my_key1=i[(Gz$xrCcCeaCrHv}[5Ryou4kz@Yh~c@K_if-p7vGQ3ZF[fEpm2SmH(Z6Yh40Ea
    at java.net.URI$Parser.fail(URI.java:2825)
    at java.net.URI$Parser.checkChars(URI.java:2998)
    at java.net.URI$Parser.parseHierarchical(URI.java:3088)
    at java.net.URI$Parser.parse(URI.java:3030)
    at java.net.URI.<init>(URI.java:595)
    at java.net.URI.create(URI.java:857)
    ... 6 more

As far as I can tell, the 65th character is an "H"...so what's going on here?!? In addition to figuring out what's wrong with my URI, the next obvious question is: what can I do to fix this? Do I need to base-64 encode the URI? If so, how? Thanks in advance!

  • 2
    Try encode it with `URLEncoder.encode(String)` method. – Buhake Sindi Dec 27 '12 at 21:36
  • Thanks @BuhakeSindi (+1) - but that method is deprecated and I'd rather stick to something that is still encouraged/supported by Java! –  Dec 27 '12 at 21:38
  • Well, the `URLEncoder.encode(String, String)` is still active, you will need to specify your encoding charset. – Buhake Sindi Dec 27 '12 at 22:21

1 Answers1

2

I don't quite understand how characters are counted and where index 65 is. But the invalid characters in your URL are the curly braces (see https://stackoverflow.com/a/7109208/413337).

Why does your URL look like this? Where are these curly braces coming from?

You cannot Base64 encode the query parameter unless the server expects them that way. Furthermore, the query parameters already look as if they are Base64 encoded. But the regular character set for Base64 encoding is not URL-safe.

URL encoding the query parameters might help. See URLEncoder.encode(String, String).

Community
  • 1
  • 1
Codo
  • 75,595
  • 17
  • 168
  • 206
  • Like `String uri = "http://a.example.com/12/allrigh/bouncer?my_key1=" + URLEncoder.encode("i[(Gz$xrCcCeaCrHv}[5Ryou4kz@Yh~c@K_if-p7vGQ3ZF[fEpm2SmH(Z6Yh40Ea", "ISO-8859-1");` – Joop Eggen Dec 27 '12 at 21:45