URISyntaxException - how to deal with URLs with%

I am new to Java and have encountered this problem. I tried the search but did not get the correct answer.

I have a string like

String name = anything 10%-20% 04-03-07

Now I need to create a url string with this string name, as shown below.

http://something.com/test/anything 10%-20% 04-03-07

I tried replacing spaces with% 20 and now I get a new url as

http://something.com/test/anything%2010%-20%%2004-03-07

When I use this url and run it in firefox, it just works fine, but when processing in Java it seems to throw

Exception in thread "main" java.lang.IllegalArgumentException
at java.net.URI.create(Unknown Source)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
Caused by: java.net.URISyntaxException: Malformed escape pair at index 39 : 
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.scanEscape(Unknown Source)
at java.net.URI$Parser.scan(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.<init>(Unknown Source)
... 6 more

This is a code throw error

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
+5
source share
2 answers

Encode also the percent sign with %25.

http://something.com/test/anything 10%-20% 04-03-07will work with http://something.com/test/anything%2010%25-20%25%2004-03-07.

URLEncoder.encode - , urlencode , - , -

String encodedUrl =
    String.format("http://something.com/%s/%s",
      URLEncoder.encode("test", "UTF-8"),
      URLEncoder.encode("anything 10%-20% 04-03-07", "UTF-8")
    );

: URLEncoder + %20, , .

+5

java.net.URI, uri

String url = "http://something.com/test/anything 10%-20% 04-03-07"

URI uri = new URI(
    url,
    null);
String request = uri.toASCIIString();

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(request);
HttpResponse response = httpclient.execute(httpget);
-1

All Articles