Подтвердить что ты не робот

Обработка перенаправления HttpClient

Я отправляю некоторые данные на сервер, который отвечает на 302 Moved Temporarily.

Я хочу, чтобы HttpClient выполнил перенаправление и автоматически GET новое местоположение, так как я считаю, что это поведение по умолчанию HttpClient. Однако я получаю исключение и не следую за перенаправлением: (

Здесь будет рассмотрен соответствующий фрагмент кода, любые идеи:

HttpParams httpParams = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParams, true);
SchemeRegistry schemeRegistry = registerFactories();
ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

HttpClient httpClient = new DefaultHttpClient(clientConnectionManager, httpParams)
HttpPost postRequest = new HttpPost(url);
postRequest.setHeader(HTTP.CONTENT_TYPE, contentType);
postRequest.setHeader(ACCEPT, contentType);

if (requestBodyString != null) {
    postRequest.setEntity(new StringEntity(requestBodyString));
}

return httpClient.execute(postRequest, responseHandler);
4b9b3361

Ответ 1

Поведение HttpClient по умолчанию соответствует требованиям спецификации HTTP (RFC 2616)

10.3.3 302 Found
...

   If the 302 status code is received in response to a request other
   than GET or HEAD, the user agent MUST NOT automatically redirect the
   request unless it can be confirmed by the user, since this might
   change the conditions under which the request was issued.

Вы можете переопределить поведение по умолчанию HttpClient по подклассу DefaultRedirectStrategy и переопределить его метод #isRedirected().

Ответ 2

Для HttpClient 4.3:

HttpClient instance = HttpClientBuilder.create()
                     .setRedirectStrategy(new LaxRedirectStrategy()).build();

Для HttpClient 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());

Для HttpClient < 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
    /** Redirectable methods. */
    private String[] REDIRECT_METHODS = new String[] { 
        HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME 
    };

    @Override
    protected boolean isRedirectable(String method) {
        for (String m : REDIRECT_METHODS) {
            if (m.equalsIgnoreCase(method)) {
                return true;
            }
        }
        return false;
    }
});

Ответ 3

Кажется, перенаправление по умолчанию отключено по умолчанию. Я пытаюсь включить, он работает, но у меня все еще есть ошибка с моей проблемой. Но мы по-прежнему можем прагматично обрабатывать перенаправление. Я думаю, что ваша проблема может решить: Итак, старый код:

AndroidHttpClient httpClient = AndroidHttpClient.newInstance("User-Agent");
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
long contentSize = httpResponse.getEntity().getContentLength();

Этот код вернет contentSize = -1, если http redirect happend

И затем я обрабатываю перенаправление самостоятельно после попытки включить перенаправление по умолчанию после

AndroidHttpClient client;
HttpGet httpGet;
HttpResponse response;
HttpHeader httpHeader;
private void handleHTTPRedirect(String url) throws IOException {
    if (client != null)
        client.close();

    client = AndroidHttpClient.newInstance("User-Agent");
    httpGet = new HttpGet(Network.encodeUrl(url));
    response = client.execute(httpGet);
    httpHeader = response.getHeaders("Location");
    while (httpHeader.length > 0) {
        client.close();
        client = AndroidHttpClient.newInstance("User-Agent");

        httpGet = new HttpGet(Network.encodeUrl(httpHeader[0].getValue()));
        response = client.execute(httpGet);
        httpHeader = response.getHeaders("Location");
    }
}

В использовании

handleHTTPRedirect(url);
long contentSize = httpResponse.getEntity().getContentLength();

Спасибо Нгуен

Ответ 4

Мое решение использует HttClient. Я должен был отправить ответ обратно вызывающему. Это мое решение

    CloseableHttpClient httpClient = HttpClients.custom()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();

    //this reads the input stream from POST
    ServletInputStream str = request.getInputStream();

    HttpPost httpPost = new HttpPost(path);
    HttpEntity postParams = new InputStreamEntity(str);
    httpPost.setEntity(postParams);

    HttpResponse httpResponse = null ;
    int responseCode = -1 ;
    StringBuffer response  = new StringBuffer();

    try {

        httpResponse = httpClient.execute(httpPost);

        responseCode = httpResponse.getStatusLine().getStatusCode();
        logger.info("POST Response Status::  {} for file {}  ", responseCode, request.getQueryString());

        //return httpResponse ;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        logger.info(" Final Complete Response {}  " + response.toString());
        httpClient.close();

    } catch (Exception e) {

        logger.error("Exception ", e);

    } finally {

        IOUtils.closeQuietly(httpClient);

    }

    // Return the response back to caller
    return  new ResponseEntity<String>(response.toString(), HttpStatus.ACCEPTED);