1

This is my url

String serverUrl = http://mob.krill.order-line.co.uk/MobileService.svc/UploadFile/721/Universal Image Loader @#&=+-_.,!()~'%20.png

here Universal Image Loader @#&=+-_.,!()~'%20.png is just name of file which is dynamically given to string.

HttpPost httpPost = new HttpPost(serverUrl);

I get:

java.lang.IllegalArgumentException: Illegal character in path at index 76: http://mob.krill.order-line.co.uk/MobileService.svc/UploadFile/721/Universal Image Loader @#&=+-_.,!()~'%20.png

what are the remedies?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Kevan
  • 67
  • 1
  • 8

2 Answers2

5

You should URL encode the String.

String encoded = URLEncoder.encode (
    "http://mob.krill.order-line.co.uk/MobileService.svc/UploadFile/721/Universal Image Loader @#&=+-_.,!()~'%20.png",
    "UTF-8");
HttpPost httpPost = new HttpPost(encoded);

EDIT, as was correctly commented by Duncan, if your URL contained a query String, which contains the characters ? and &, you wouldn't want to URL-encode those. You would only encode the Strings containing problematic characters.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Most things [I've read](http://stackoverflow.com/a/10786112/474189) suggest that the encoding should only be done on the "dodgy" parts of the URL. Your approach would work in this case, but wouldn't if query strings were used in due course. It would be better to split the URL to identify just the `Universal Image Loader @#&=+-_.,!()~'%20.png` part. – Duncan Jones Aug 15 '14 at 14:30
  • @Duncan: Thanks for your suggestions! solution found by your comment! – Kevan Aug 15 '14 at 14:47
1

As per above suggestion my code worked with below solution

String fileName = f.getName();
            try {
                fileName = URLEncoder.encode(fileName,"UTF-8");
            } catch (UnsupportedEncodingException e1) {             
                e1.printStackTrace();
            }
            String serverUrl = http://mob.krill.order-line.co.uk/MobileService.svc/UploadFile/721/+fileName;
Kevan
  • 67
  • 1
  • 8