Android HttpURLConnection and URLs with special characters

Consider the following code (which receives a response from an HTTP request and prints it). NOTE. This code works in a standard Java application. When using the code in an Android app, I only see the problem indicated below.

public class RetrieveHTMLTest { public static void main(String [] args) { getListing(args[0); } public static void getListing(String stringURL) { HttpURLConnection conn = null; String html = ""; String line = null; BufferedReader reader = null; URL url = null; try { url = new URL(stringURL); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(6000); conn.setReadTimeout(6000); conn.setRequestMethod("GET"); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); conn.connect(); while ((line = reader.readLine()) != null) { html = html + line; } System.out.println(html); reader.close(); conn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } finally { } } } 

If I put the url: <b> Http: // somehost / somepath /

The following code is working fine. But, if I change the URL: http: // somehost / somepath [comment] / The code throws a timeout exception due to the characters "[" and "]".

If I changed the URL to: <b> Http: // somehost / somepath% 20% 5BA% 20comment% 5D / Code works fine. Again, since there are no "[" and "]" characters.

My question is: how do I get the url:

http: // somehost / somepath [comment] /

in the following format:

HTTP: // somehost / somepath% 20% 5BA% 20comment% 5D /

Also, should I continue to use HttpURLConnection in Android, since it cannot accept URLs with special characters? Should the standard always convert a URL before using HttpURLConnection?

+4
source share
2 answers

Use the URLEncoder class:

 URLEncoder.encode(value, "utf-8"); 

More details here .

Edit: this method should only be used to encode parameter values. DO NOT encode the entire URL. For example, if you have a URL: http://www.somesite.com?param1=value1¶m2=value2 then you only need to encode value1 and value2, and then form the URL using encoded versions of these values.

+12
source
 url = URLEncoder.encode(value, "utf-8"); url = url.replaceAll("\\+", "%20"); 

"+" cannot be returned

+2
source

Source: https://habr.com/ru/post/1384828/


All Articles