解压缩Apache httpclient结果

时间:2017-11-10 03:13:23

标签: apache-httpclient-4.x apache-httpcomponents

我正在使用Apache HTTPClient 4.5.3发出一些HTTP请求,但是我得到了一个g-zipped响应我尝试过很多我在网上找到的东西但是没有用过。打印回复时,我仍然感到胡言乱语。以下是相关代码。我需要做些什么来获得人类可读的响应?

static public CloseableHttpClient CreateHttpClient() {
    // return
    // HttpClients.custom().disableAutomaticRetries().setHttpProcessor(HttpProcessorBuilder.create().build())
    // .build();

    return HttpClientBuilder.create().disableAutomaticRetries()
            .setHttpProcessor(HttpProcessorBuilder.create().build()).build();
}

static public RequestConfig GetConfig() {
    return RequestConfig.custom().setSocketTimeout(READTIMEOUT).setConnectTimeout(CONNECTTIMEOUT)
            .setConnectionRequestTimeout(REQUESTTIMEOUT).build();
}

static public String updates() {
    String result = "";
    String url = "https://example.com";
    CloseableHttpClient httpClient = CreateHttpClient();
    CloseableHttpResponse response = null;
    URL urlObj;
    RequestConfig config = GetConfig();

    try {
        urlObj = new URL(url);

        HttpPost request = new HttpPost(url);
        request.setConfig(config);

        StringEntity params = new StringEntity("example");

        request.addHeader("Accept-Language", "en");
        request.addHeader("Content-Type", "application/json; charset=UTF-8");
        request.addHeader("Content-Length", String.valueOf(params.getContentLength()));
        request.addHeader("Host", urlObj.getHost());
        request.addHeader("Connection", "Keep-Alive");
        request.addHeader("Accept-Encoding", "gzip");

        request.setEntity(params);
        response = httpClient.execute(request);

        int responseCode = response.getStatusLine().getStatusCode();

        System.out.println("updates response code: " + responseCode);


        // BufferedReader rd = new BufferedReader(new
        // InputStreamReader(response.getEntity().getContent(), "UTF-8"));

        result = EntityUtils.toString(response.getEntity());
        // String line = "";
        // while ((line = rd.readLine()) != null) {
        // result.append(line);
        // }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (response != null)
                response.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

1 个答案:

答案 0 :(得分:1)

您应该从响应实体获取 InputStream 的内容。您可以使用BufferedReader

InputStream 创建一个String
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();
    String result = convertInputStreamToString(instream); 
    instream.close();
}

编写自己的convertInputStreamToString。如果您在此处需要帮助,请执行以下操作:  Read/convert an InputStream to a String