William Seemann
William Seemann

Reputation: 3530

Android HttpURLConnection and URL with special characters

Consider this following code (that retrieves the response from a HTTP request and prints it). NOTE: This code works in a standard Java application. I only experience the problem listed below when using the code in an Android application.

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 supply the URL: http://somehost/somepath/

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

If I change the URL to: http://somehost/somepath%20%5Ba%20comment%5D/ The code works fine. Again, because the "[" and "]" characters aren't present.

My question is, how do I get the URL:

http://somehost/somepath [a comment]/

into the following format:

http://somehost/somepath%20%5Ba%20comment%5D/

Also, should I continue using HttpURLConnection in Android since it can't accept a URL with special characters? If the standard to always convert the URL before using HttpURLConnection?

Upvotes: 6

Views: 10671

Answers (2)

brian
brian

Reputation: 6922

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

the "+" may not be revert

Upvotes: 2

Arnab Chakraborty
Arnab Chakraborty

Reputation: 7472

Use the URLEncoder class :

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

You can find more details here.

Edit : You should use this method only to encode your parameter values. DO NOT encode the entire URL. For example if you have a url like : http://www.somesite.com?param1=value1&param2=value2 then you should only encode value1 and value2 and then form the url using encoded versions of these values.

Upvotes: 14

Related Questions