DavidNg
DavidNg

Reputation: 2836

Java: download web content with special characters in url

I am downloading a webpage content but the address has special characters. For example, it contain word adiós in the myUrl. I am using the below code, but it is not successful. Do you have any suggestion? Thanks

String myUrl="http://www.somethingxxxxx.com/adiós";   
URLConnection yc = new URL(myUrl).openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
                                                yc.getInputStream()));

Upvotes: 0

Views: 387

Answers (2)

davidbuzatto
davidbuzatto

Reputation: 9424

You just need to encode your URL before you use it. To do this, you can try something like:

try {
    String base = "http://www.somethingxxxxx.com/";
    String toEncode = "adiós";
    String myEncodedUrl = base + URLEncoder.encode( toEncode, "UTF-8" );
    URLConnection yc = new URL(myEncodedUrl).openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
                                            yc.getInputStream()));
} catch ( UnsupportedEncodingException exc ) {
   exc.printStackTrace();
} catch ( IOException exc ) {
   exc.printStackTrace();
}

Upvotes: 1

Chris
Chris

Reputation: 5654

Use URLEncoder class instead of java.netURL

Upvotes: 2

Related Questions