Sunday, September 20, 2009

Fetch HTTP content in Java

Since programming for Android, I hit my head against every possible snag in the Java programming language. For example, I have to fetch the content of a URL. In PHP, I'd simply do: $data = file_get_contents($url); But no, in Java, no such easiness for you! I had to write my own helper function: public static String getUrlContent(String sUrl) throws Exception { URL url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String content = "", line; while ((line = rd.readLine()) != null) { content += line + "\n"; } return content; } Seems very hackish, especially the line starting with BufferedReader. The whole function is actually composed of bits of code found around the web. Bah, why didn't Google choose Python as their default programming language for Android?

1 comment:

  1. Holy moly, I feel you man. I'm currently trying to fix up some java code that grabs URLs from the internet and having a heck of a time doing it. I have an implementation very similiar to yours, but unfortunately I can't seem to get it to work on all URLs... did you ever get yours functioning all of the way?

    ReplyDelete