Apache HttpClient 5.x中setRelativeRedirectsAllowed()替代方案咨询
Apache HttpClient 4.x 到 5.x 迁移:
setRelativeRedirectsAllowed 替代方案 1. HttpClient 5.x 中的替代方案
在 HttpClient 5.x 中,RequestConfig 类的 setRelativeRedirectsAllowed() 方法已被移除,因为默认重定向策略(DefaultRedirectStrategy)已经默认允许相对URL的重定向,无需单独配置该参数。
你可以直接简化原4.x的RequestConfig配置,移除setRelativeRedirectsAllowed(true),5.x的默认行为就会对应原4.x开启该参数的效果。
5.x版本的基础配置示例:
final RequestConfig requestConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .setConnectionRequestTimeout(...) .setConnectTimeout(...) .setRedirectsEnabled(true) // 仅需开启重定向即可,默认允许相对重定向 .setSocketTimeout(...) .build(); final CloseableHttpClient client = HttpClients.custom() // 注意5.x中HttpClientBuilder改为HttpClients .setDefaultRequestConfig(requestConfig) .build(); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
2. 自定义控制相对重定向的实现
如果你的业务需要更精细的控制(比如仅在特定场景下允许/禁止相对重定向),可以通过自定义RedirectStrategy来实现:
步骤1:实现自定义RedirectStrategy
import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.net.URIBuilder; import java.net.URI; import java.net.URISyntaxException; public class CustomRedirectStrategy extends DefaultRedirectStrategy { private final boolean allowRelativeRedirects; public CustomRedirectStrategy(boolean allowRelativeRedirects) { this.allowRelativeRedirects = allowRelativeRedirects; } @Override protected URI createLocationURI(final String location, final HttpRequest request, final HttpResponse response, final HttpClientContext context) throws ProtocolException { try { URI locationUri = new URI(location); // 判断是否为相对URI(无scheme和主机信息) if (!allowRelativeRedirects && !locationUri.isAbsolute()) { throw new ProtocolException("Relative redirects are not allowed: " + location); } // 如果是相对URI且允许,基于原请求URI构建绝对URI if (!locationUri.isAbsolute()) { URI originalUri = request.getUri(); locationUri = new URIBuilder(originalUri) .setPath(locationUri.getPath()) .setQuery(locationUri.getQuery()) .build(); } return locationUri; } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } } }
步骤2:将自定义策略配置到HttpClient
final CloseableHttpClient client = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setRedirectStrategy(new CustomRedirectStrategy(true)) // 传入true允许,false禁止 .build();
内容的提问来源于stack exchange,提问作者authorizeduser
相关产品推荐
相关产品推荐

