调用httpClient方法出现的302重定向问题

调用第三方接口之后,发现对方返回的url经过重定向了,而调用doGet方法始终会抛出重定向的异常,该接口一直获取不到正常返回值。

正如图中所示,也就是重定向异常失效的意思。

解决办法如下:

  String url = "https://abc.com/login"+ "?id=" + MD5.sign("xxx") + "&password=" + "xxx";
  logger.info("request url : " + url);
        try{
            RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
            CloseableHttpClient httpClient  = HttpClients.custom().setDefaultRequestConfig(config).build();
            HttpResponse response = httpClient.execute(new HttpGet(url));
            if(response.getStatusLine().getStatusCode()==302){
                // 跳转的目标地址是在 HTTP-HEAD 中的
                Header header = response.getFirstHeader("location");
                // 这就是跳转后的地址
                newUrl = header.getValue();
            }
        }catch(Exception e){
            return WebResponse.resFail("异常信息",e);
        }

从http-head中提取出重定向后的url就好了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HTTP状态码302表示重定向,服务器向客户端返回该状态码时,意味着客户端需要重新发送请求到新的URL地址。所以,在您的情况下,服务器可能返回了302状态码,要求您的客户端重新发送请求到新的URL地址。 您可以尝试使用HttpClient的RedirectStrategy来处理重定向。以下是一个示例代码,展示如何在HttpClient中使用RedirectStrategy: ```java import org.apache.http.HttpEntity; 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; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.custom() .setRedirectStrategy(new LaxRedirectStrategy()) .build(); HttpGet httpGet = new HttpGet("http://www.example.com"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } } } ``` 在上面的示例代码中,我们使用了 `LaxRedirectStrategy` 来处理重定向。`LaxRedirectStrategy` 会自动重定向所有的HTTP方法,包括POST、PUT等。如果您只需要重定向GET请求,可以使用 `DefaultRedirectStrategy`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值