java httpclient 重定向_如何在HttpClient中自动重定向(java,apache)

我创建了httpClient并设置了设置

HttpClient client = new HttpClient();

client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

client.getParams().setContentCharset("UTF-8");

第一次请求(获取)

GetMethod first = new GetMethod("http://vk.com");

int returnCode = client.executeMethod(first);

BufferedReader br = null;

String lineResult = "";

if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {

System.err.println("The Post method is not implemented by this URI");

// still consume the response body

first.getResponseBodyAsString();

} else {

br = new BufferedReader(new InputStreamReader(first.getResponseBodyAsStream(), Charset.forName("windows-1251")));

String readLine = "";

while (((readLine = br.readLine()) != null)) {

lineResult += readLine;

}

}

回应正确.

第二个请求(帖子):

PostMethod second = new PostMethod("http://login.vk.com/?act=login");

second.setRequestHeader("Referer", "http://vk.com/");

second.addParameter("act", "login");

second.addParameter("al_frame", "1");

second.addParameter("captcha_key", "");

second.addParameter("captcha_sid", "");

second.addParameter("expire", "");

second.addParameter("q", "1");

second.addParameter("from_host", "vk.com");

second.addParameter("email", email);

second.addParameter("pass", password);

returnCode = client.executeMethod(second);

br = null;

lineResult = "";

if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {

System.err.println("The Post method is not implemented by this URI");

// still consume the response body

second.getResponseBodyAsString();

} else {

br = new BufferedReader(new InputStreamReader(second.getResponseBodyAsStream()));

String readLine = "";

while (((readLine = br.readLine()) != null)) {

lineResult += readLine;

}

}

这个响应也是正确的,但我需要重定向到Headers.Location.

我不知道如何从Headers Location获取价值或如何自动启用重定向.

### 如何在 Apache HttpClient 中启用自动重定向 Apache HttpClient 提供了内置支持来处理 HTTP 响应中的重定向。默认情况下,`DefaultHttpClient` 或 `CloseableHttpClient` 可以通过设置特定参数来启用或禁用自动重定向功能。 以下是实现自动重定向的关键方法: #### 设置自动重定向 可以通过 `HttpClientBuilder` 的 `setRedirectStrategy` 方法自定义重定向策略。如果希望使用默认的重定向逻辑,则可以依赖于 `DefaultRedirectStrategy` 类[^1]。 下面是一个完整的代码示例展示如何启用自动重定向: ```java import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class RedirectExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom().build()) .setRedirectStrategy(new DefaultRedirectStrategy()) // 启用默认重定向策略 .build(); try { HttpGet httpGet = new HttpGet("http://example.com"); CloseableHttpResponse response = httpClient.execute(httpGet); try { System.out.println(response.getStatusLine()); } finally { response.close(); } } finally { httpClient.close(); } } } ``` 在此代码片段中: - 使用 `HttpClients.custom()` 创建了一个可配置的客户端实例。 - 调用了 `.setRedirectStrategy(new DefaultRedirectStrategy())` 来启用默认的重定向机制[^1]。 - 如果服务器返回的是 3xx 状态码(例如 301 Moved Permanently 或 302 Found),则 HttpClient 将会自动跟随这些重定向请求并获取最终的目标资源。 需要注意的是,默认情况下,`DefaultHttpClient` 和 `CloseableHttpClient` 已经启用了自动重定向功能。因此,在大多数场景下无需显式调用 `setRedirectStrategy` 方法即可正常工作。 --- #### 自定义重定向策略 如果需要更复杂的控制行为,比如仅允许某些类型的重定向或者限制最大跳转次数,可以继承 `DefaultRedirectStrategy` 并覆盖其方法。例如: ```java import org.apache.http.client.RedirectStrategy; import org.apache.http.protocol.HttpContext; import java.io.IOException; import java.net.URI; public class CustomRedirectStrategy extends DefaultRedirectStrategy { private int maxRedirects = 5; // 最大重定向次数 @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { if (response.getCode() >= 300 && response.getCode() < 400) { return true; } return false; } @Override public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { String locationHeader = response.getFirstHeader("Location").getValue(); return URI.create(locationHeader); } @Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); if ("GET".equalsIgnoreCase(request.getRequestLine().getMethod())) { return new HttpGet(uri); } throw new ProtocolException("Unsupported redirect method."); } } ``` 此自定义类可以根据业务需求调整重定向的行为,并将其应用到 HttpClient 实例中。 --- #### 关闭自动重定向 有时可能不希望 HttpClient 处理任何重定向操作。这种情况下,可以传递一个永远不会触发重定向的策略对象给 `setRedirectStrategy` 方法: ```java httpClient.setRedirectStrategy(new LaxRedirectStrategy() { @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return false; // 完全关闭重定向 } }); ``` 这样即使接收到 3xx 响应也不会尝试访问新的 URL 地址。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值