title: Open an HTTP-connection to the "final" (non-redirected) URL
body: <p><strong>Given a URL string, I want to get an HTTP-connection to the "final" (non-redirected) URL:</strong></p>
  
  <ul>
  <li><p>If the response-code is 2xx, then I can simply use the initial connection.</p></li>
  <li><p>If the response-code is 3xx, then I need to open a new connection and try again.</p></li>
  <li><p>For any other response-code (such as 4xx or 5xx), I "give up" and return <code>null</code>.</p></li>
  </ul>
  
  <p><strong>My code is given below:</strong></p>
  
  <pre><code>HttpURLConnection getConnection(String url) throws Exception
  {
      HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
      while (true)
      {
          connection.setInstanceFollowRedirects(true);
          connection.setRequestProperty("User-Agent","");
          int responseCode = connection.getResponseCode();
          switch (responseCode/100)
          {
          case 2:
              return connection;
          case 3:
              switch (responseCode)
              {
              case 300:
                  connection = ???
                  break;
              case 301:
              case 302:
              case 303:
              case 305:
              case 307:
                  connection = (HttpURLConnection)new URL(connection.getHeaderField("Location")).openConnection();
                  break;
              case 304:
                  connection = ???
                  break;
              default:
                  return null;
              }
              break;
          default:
              return null;
          }
      }
  }
  </code></pre>
  
  <p><strong>My questions are hereby:</strong></p>
  
  <ol>
  <li><p>How should I handle response-codes 300 and 304?</p></li>
  <li><p>Am I handling response-codes 301, 302, 303, 305 and 307 correctly?</p></li>
  </ol>
  
  <p><strong>Any other constructive comments on the method above will also be appreciated.</strong></p>
  
  <p>Thanks</p>