Java / Apache HTTP客户端 - 如何获取POST URL重定向链

时间:2015-06-07 00:28:13

标签: java apache rest httpclient url-redirection

我通过发送POST请求来使用REST服务,响应返回302状态代码并包含指向资源新位置的“Location”标头。在Chrome的Advanced Rest Client上发送请求时,它会将所有重定向网址显示为重定向#1#2#3。

问题是有2个重定向网址(有时是3个),我无法获得重定向链来获取第二个位置标头,这是唯一一个在任何浏览器上都没有cookie的情况。

有人可以告诉我如何获取重定向网址链吗? 提前谢谢!

protected HttpEntity sendPost(String url, String contentType) throws Exception
{
    logger.info("Sending SSO parameters to " + url);

    CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();

    HttpPost httpPost = new HttpPost(url);
    if (contentType != null)
    {
        httpPost.setHeader("Content-Type", contentType);
    }

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);

    httpPost.setEntity(entity);

    CloseableHttpResponse response = httpClient.execute(httpPost);

    StatusLine s = response.getStatusLine();

    if (validateResponseStatusCode)
    {
        if (s.getStatusCode() != 200 && s.getStatusCode() != 201)
        {
            logger.debug("Error on POST request. REST procedure returned status " + s.getStatusCode() + " "
                    + response.getStatusLine().getReasonPhrase());

            throw new Exception("Error executing REST procedure. Returned status is: " + s.getStatusCode() + " "
                    + response.getStatusLine().getReasonPhrase());
        }
    }

    redirectLocationURL = getHeaderValue(RestHeader.Location, response);

    statusCode = s.getStatusCode();

    return response.getEntity();
}

protected String getHeaderValue(RestHeader headerName, HttpResponse response)
{
    String headerValue = "";

    logger.info("Getting header '" + headerName + "'");

    for (Header currentHeader : response.getAllHeaders())
    {
        if (currentHeader.getName().equals(headerName.toString()))
        {
            headerValue = currentHeader.getValue();
            logger.info("'" + headerName + "' header value is: " + headerValue);
            break;
        }
    }

    if (headerValue.equalsIgnoreCase(""))
    {
        logger.info("Header '" + headerName + "' not found in HTTP Response");
        return null;
    }

    return headerValue;
}

0 个答案:

没有答案