Best practice sending HTTP GET requests

http-get, java

Solution

I think the two simple changes you should make are to close your input stream in a `finally` block, and use a `StringBuilder` instead of `StringBuffer`.

Furthermore, you may want to check the response code and throw an exception if you receive an error response (400+, 500+, etc).

Edit:

If you are planning on buffering all of the content anyways, and you do not mind using libraries, then you can simply do:

Request.Get("http://some.url").execute().returnContent();

Using Apache HttpComponents.

Problem

Is there better practice for sending HTTP GET requests than the following? ``` private StringBuffer getData(String url) throws Exception { URL obj; obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response; } ```

Original source