How to get HttpClient returning status code and response body?

后端 未结 5 2091
谎友^
谎友^ 2020-11-29 08:03

I am trying to get Apache HttpClient to fire an HTTP request, and then display the HTTP response code (200, 404, 500, etc.) as well as the HTTP response body (text string).

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 08:33

    Fluent facade API:

    Response response = Request.Get(uri)
            .connectTimeout(MILLIS_ONE_SECOND)
            .socketTimeout(MILLIS_ONE_SECOND)
            .execute();
    HttpResponse httpResponse = response.returnResponse();
    StatusLine statusLine = httpResponse.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
        // 响应内容编码自适应?(好像没那么智能)
        String responseContent = EntityUtils.toString(
                httpResponse.getEntity(), StandardCharsets.UTF_8.name());
    }
    

提交回复
热议问题