http-клиент apache org.apache.http.NoHttpResponseException: целевой сервер не ответил

Я использую http-клиент apache для тестирования своего WS. Я написал получить WS в джерси. URL для этого WS

http://localhost:8080/mobilestore/rest/sysgestockmobilews/getinventory?xml=dataString

чтобы вызвать этот WS, используя URL-адрес, я должен написать метод, который выглядит следующим образом

public static void getInventory(String input)
        throws ClientProtocolException, IOException {

    System.out.println(input);
    String url = URL + "getinventory";
    HttpClient client = new DefaultHttpClient();

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("xml", input));
    String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
    url += "?" + paramString;
    System.out.println(url);
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response
            .getEntity().getContent()));

    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }

}

Теперь, когда я запускаю программу и передаю URL-адрес этой функции, я получаю исключение в строке

HttpResponse response = client.execute(request);

Исключение следующее

Aug 14, 2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (org.apache.http.NoHttpResponseException) caught when processing         request: The target server failed to respond
Aug 14, 2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request
Aug 14, 2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (org.apache.http.NoHttpResponseException) caught when processing   request: The target server failed to respond
Aug 14, 2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request
Aug 14, 2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (org.apache.http.NoHttpResponseException) caught when processing      request: The target server failed to respond
Aug 14, 2013 9:31:50 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request
Exception in thread "main" org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at    org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.tainosystems.http.client.TestWs.getInventory(TestWs.java:66)
at com.tainosystems.http.client.TestWs.main(TestWs.java:47)

Теперь, если я использую URL-адрес WS и нажимаю его с помощью любого браузера, я получаю ожидаемый результат, но я хочу знать, что не так с моим клиентским кодом apache http.


person Waqas Ali    schedule 14.08.2013    source источник
comment
Точно такая же проблема была опубликована здесь: /10558791/   -  person pls    schedule 21.01.2015


Ответы (1)


Я прошел по ссылкам отсюда и получил этот ответ: получить NoHttpResponseException для нагрузочного тестирования

Это поставило меня на правильный путь. Чтобы немного обновить ответ, вот решение, использующее текущий API http-client 4.5:

private final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(createHttpClient());

private CloseableHttpClient createHttpClient() {
    return HttpClients.custom().setRetryHandler((exception, executionCount, context) -> {
            if (executionCount > 3) {
                LOGGER.warn("Maximum tries reached for client http pool ");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                LOGGER.warn("No response from server on " + executionCount + " call");
                return true;
            }
            return false;
        }).build();
}

Я также использую там spring-web, поэтому я использовал клиент в качестве параметра для фабрики RestTemplate, так как я хочу, чтобы он использовался в RestTemplate.

person Ondrej Burkert    schedule 20.06.2016