[JAVA] Correspondence when HTTP status code 302 occurs when connecting to an external URL

Overview

For example, when writing a program that downloads and fetches a file from an external site, depending on the site, it can be downloaded with a browser, but if you connect the URL from the code, an error may occur. Actually, when I check how it can be downloaded with a browser with DevTools of Chrome etc., HTTP status code 302 is returned at the URL I went to access. This time, I will write a memo about the correspondence about this HTTP status code 302.

What is HTTP Status Code 302?

As stated in the article What is HTTP status code "302 redirect", 302 is said to have a "temporary redirect". In the case of 302, the URL displayed in the browser does not change, so the user will not notice that they are redirected unless they use DevTools or the like.

How to deal with the program

When the 302 response is returned, the URL of the redirect destination is stored in the header Location. Therefore, you can reconnect to the URL stored in this Location. The StackOverflow article at here introduces the Java implementation.

Implementation sample

It's almost a copy of the StackOverflow article above, but a sample implementation.

Sample.java


public class Sample {

  //Get CSV information from PhishTank
  public void urlSample() {
    try {
      //Connect to the URL before the redirect
      URL url = new URL("https://xxxx/xxxxxx");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setInstanceFollowRedirects(false);
      String redirectLocation = conn.getHeaderField("Location");
      conn.disconnect();
      //Reconnect with the redirect URL
      URL afterRedirectUrl = new URL(redirectLocation);
      InputStreamReader in = new InputStreamReader(afterRedirectUrl.openStream());
      //After this, processing the received data
    } catch (Exception e) {
      //Error handling
    }
  }
}

Recommended Posts

Correspondence when HTTP status code 302 occurs when connecting to an external URL
[Rails] How to connect to an external API using HTTP Client (I tried connecting to Qiita API)
[Swift] Table View Cell, how to jump to an external URL
What to do when an UnsupportedCharsetException occurs in a lightweight JRE
How to insert an external library
What to do when javax.batch.operations.JobStartException occurs
What to do and how to install when an error occurs in DXRuby 1.4.7
What to do if an error occurs when nokogiri enters when bundle install