9

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?

4

3 に答える 3

10

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

Specifically:

String safeUrl = URLEncoder.encode("domain.com/service/{username}", "UTF-8");
于 2010-05-27T17:46:31.223 に答える
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;
}
于 2015-11-06T15:17:50.907 に答える
1

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.

于 2013-03-27T22:51:28.390 に答える