What are best practices for working with HttpURLConnection (legacy)?

HttpURLConnection is a part of the Java standard library, used for sending and receiving data over HTTP. Though now considered somewhat legacy with the advent of libraries like Apache HttpClient and OkHttp, it is still widely used. Here are some best practices to follow when working with HttpURLConnection.

Best Practices for HttpURLConnection

  • Always Close Connections: It's essential to close the connection to free up resources. Use try-with-resources wherever possible.
  • Set Request Properties: Customize request properties such as headers and timeouts for better control and performance.
  • Handle Exceptions Properly: Catch and handle exceptions to ensure your application remains stable in case of network issues.
  • Use InputStream and OutputStream Appropriately: Always read the response using an InputStream and write requests via an OutputStream.
  • Check Response Code: Always check the HTTP response code to determine whether a request was successful and handle errors accordingly.
  • Avoid Blocking Calls: Use a separate thread to handle network calls to avoid blocking the main application thread.

Example Code

<![CDATA[ import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) { HttpURLConnection connection = null; try { URL url = new URL("https://api.example.com/data"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("GET request not worked"); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } } ]]>

Keywords: HttpURLConnection Java HTTP networking API best practices