Prevent from stripping "?" if there are no query paramters


I am trying to use in order to make a request to a URL like this:

In order to do this, I need to construct a, but the constructor strips away the question mark "?": url = new URL("");
String string = url.toString(); 
// String is

And when I create the connection with url.openConnection(), I just get a 404.

I get why it does this. It righfully recognizes everything after and including the hash # as a url fragment, which means that the actual url becomes And then, it just strips the trailing question mark. But I need the URL to be rendered as is. This is for an Android app.

How can I force HTTPUrlConnection to make the GET request with the question mark in the URL?

Show source
| url   | java   | android   | uri   | http   2017-08-08 23:08 1 Answers

Answers to Prevent from stripping "?" if there are no query paramters ( 1 )

  1. 2017-08-09 08:08

    In a URL, the part after ? is a query string, and the part after # is a fragment identifier, as you already noted.

    While the query string is sent to the server, the fragment identifier is not, so trying to send one does not make sense.

    2 possibilities:

    • if it is a fragment identifier, you don't need to send it and Android's behavior (normalizing the URL) is correct. Stripping the trailing ? (empty query string) should not be a problem as it makes no sense alone (for both server and client). If you want to preserve the fragment in your client code, what you want is to create a URI, use that to display wherever you want, then convert to URL with toURL() when you need to speak with server.

    • if it is not actually a fragment identifier, it's supposed to be part of the query string, so you need to send a hash sign as part of the URL: in that case, you need to url-encode it to %23, the part after the ? won't be stripped, and the server will know what to do with the encoded %23.

Leave a reply to - Prevent from stripping "?" if there are no query paramters

◀ Go back