Use HttpGet with illegal characters in url

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}). Obviously, the web service assignment is poorly written, but I cannot change it.

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

The URL, although it has illegal characters, works from a browser, but the HttpGet implementation HttpGet not allow me to use it. What should I do or use instead to avoid this problem?

+7
source share
3 answers

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

In particular:

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

This question is old, but it helped me, and I just wanted to add for everyone who could come that I fixed this problem in my application with a variation of Mike's answer.

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

I found that encoding only the relevant parts worked when trying to encode the entire URL caused an error for me.

+1
source

we should not use URLEncoder.encode for the address part of the url because it incorrectly changes your http://domain.com/ {username} to http% 3A% 2F% 2Fdomain.com% 2 {username} and you should know that it will replace all spaces with "+" so that I would be better off replacing them with "% 20".

Here, this function encodes only the last part of your URL, which is {username} or a file name or something 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; } 
+1
source

All Articles