How do I handle HTTP redirects in Java using HttpURLConnection?
Handling HTTP redirects in Java using HttpURLConnection is fairly straightforward. It involves processing the HTTP response code and manually following the redirection if the server responds with a 3xx status code. Here’s a step-by-step guide: 1. Set up the HTTP connection: Create a HttpURLConnection instance and configure it for the initial request. Set the allowed […]
Artikel oleh Wayan · Sumber: Kode Java ↗
Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.
Handling HTTP redirects in Java using HttpURLConnection is fairly straightforward. It involves processing the HTTP response code and manually following the redirection if the server responds with a 3xx status code.
Here’s a step-by-step guide:
1. Set up the HTTP connection:
- Create a
HttpURLConnectioninstance and configure it for the initial request. - Set the allowed HTTP method (such as
GETorPOST).
2. Handle redirects:
- Check if the response code from the server is a redirect status (3xx).
- If it is, retrieve the
Locationheader from the response. This header contains the URL to redirect to. - Open a new connection with the redirected URL.
3. Repeat if necessary:
- Redirects may happen multiple times. You’ll need to handle all of them until a non-redirect response (like 200 or 204) is received.
Sample Code:
Here’s how you can implement redirect handling with HttpURLConnection:
package org.kodejava.net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPRedirectHandler {
public static void main(String[] args) {
try {
String initialUrl = "http://kodejava.org";
String response = fetchWithRedirects(initialUrl);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String fetchWithRedirects(String urlString) throws Exception {
int maxRedirects = 5; // Limit the number of redirects to prevent infinite loops
int redirectCount = 0;
while (true) {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false); // Disable automatic redirects
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000); // 5s timeout
connection.setReadTimeout(5000);
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println("Response Code = " + responseCode);
// Handle redirect (HTTP 3xx)
if (responseCode >= 300 && responseCode < 400) {
redirectCount++;
if (redirectCount > maxRedirects) {
throw new Exception("Too many redirects");
}
// Get the "Location" header field for the new URL
String newUrl = connection.getHeaderField("Location");
if (newUrl == null) {
throw new Exception("Redirect URL not provided by server!");
}
urlString = newUrl;
System.out.println("Redirecting to: " + newUrl);
continue;
} else if (responseCode == HttpURLConnection.HTTP_OK) {
// Successful response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder responseBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
reader.close();
return responseBuilder.toString();
} else {
throw new Exception("HTTP response error: " + responseCode);
}
}
}
}
Explanation of Key Points:
- Instance Follow Redirects:
- By default,
HttpURLConnectionmay handle redirects automatically. However, settingsetInstanceFollowRedirects(false)allows you to customize how redirects are handled.
- By default,
- Limit Redirects with a Counter:
- Redirect loops can cause infinite recursion, so limit the number of allowed redirects.
- Fetching the Redirect URL:
- The
Locationheader in the response contains the URL to which the request should be redirected.
- The
- Preserve Request Properties:
- Redirects sometimes require forwarding cookies, user-agent headers, etc. Depending on your use case, you may need to preserve or modify these properties.
Advantages of This Approach:
- Full control over redirect behavior.
- Ability to log each redirection step or modify the request before redirecting.
Notes:
- If you’re looking for a higher-level tool, consider using libraries like Apache HttpClient for better flexibility and built-in redirect handling.
