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?
source share