Use HttpGet with illegal characters in the URL

18,192

Solution 1

http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html

Specifically:

String safeUrl = URLEncoder.encode("domain.com/service/{username}", "UTF-8");

Solution 2

we shouldn't use URLEncoder.encode for address part of URL because it wrongly changes your http://domain.com/{username} to http%3A%2F%2Fdomain.com%2{username} and you should know it will replace all spaces with '+' that it was better to me to replace them with "%20".

Here this function encodes only last part of your URL which is {username} or file name or anything that may have illegal characters.

String safeUrl(String inUrl)
{
    int fileInd = inUrl.lastIndexOf('/') + 1;
    String addr = inUrl.substring(0, fileInd);
    String fileName = inUrl.substring(fileInd);
    String outUrl=null;

    try {
        outUrl = addr + URLEncoder.encode(fileName, "UTF-8");
        outUrl = outUrl.replace("+", "%20");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return outUrl;
}

Solution 3

This question is old but it helped me and I just wanted to add for anyone who might come by that I fixed this issue on my app with a variation of Mike's reply.

String safeUrl = "domain.com/service/" + URLEncoder.encode("{username}", "UTF-8");

I found that encoding just the relevant parts worked, where attempting to encode the entire url caused an error for me.

Share:
18,192

Related videos on Youtube

Catalin Morosan
Author by

Catalin Morosan

Android developer

Updated on June 04, 2022

Comments

  • Catalin Morosan
    Catalin Morosan almost 2 years

    I am trying to use DefaultHttpClient and HttpGet to make a request to a web service. Unfortunately the web service URL contains illegal characters such as { (ex: domain.com/service/{username}). It's obvious that the web service naming isn't well written but I can't change it.

    When I do HttpGet(url), I get that I have an illegal character in the url (that is { and }). If I encode the URL before that, there is no error but the request goes to a different URL where there is nothing.

    The url, although has illegal characters, works from the browser but the HttpGet implementation doesn't let me use it. What should I do or use instead to avoid this problem?

  • Catalin Morosan
    Catalin Morosan almost 14 years
    Hmm. As I said in the question, I have tried encoding (exact line as yours) but it didn't work. I retried now and Success! Thanks.
  • Catalin Morosan
    Catalin Morosan almost 14 years
    The first time I tried it and failed was because the connection timeout expired.

Related