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.
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.
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.
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