在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ 這個get函數中headers.entrySet().stream()這段怎么理

這個get函數中headers.entrySet().stream()這段怎么理解?EntityUtils是干什么用的?

問題一

if (headers != null) {
            headers.entrySet().stream().forEach(
                    entry -> {
                        httpGet.setHeader(entry.getKey(), entry.getValue());
                    }
            );
        }

這段是什么意思?

問題二

EntityUtils.toString(httpResponse.getEntity(),"UTF-8");

這句是什么意思?

源碼

import org.apache.http.util.EntityUtils;

public static String get(CloseableHttpClient httpClient, String url, Map<String, String> headers) throws ClientProtocolException, IOException {
        HttpGet httpGet = new HttpGet(url);
        if (headers != null) {
            headers.entrySet().stream().forEach(
                    entry -> {
                        httpGet.setHeader(entry.getKey(), entry.getValue());
                    }
            );
        }
        HttpResponse httpResponse = httpClient.execute(httpGet);
        int code = httpResponse.getStatusLine().getStatusCode();
        if (code >= 299) {
            log.error("status code is {}", code);
        }
        return EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
    }
回答
編輯回答
膽怯

問題一:

把一個(可能是 HashMap)headers 數據通過 stream 的方式調用 httpGet.setHeader 來添加到請求頭。
entrySet 是一個 鍵值對 對象。

問題二:

httpResponse.getEntity() 是返回這次回復(即 request 的響應)的實體信息,也就是整個 HTTP 響應內容,包括頭部、數據區(qū)。

EntityUtils.toString(httpResponse.getEntity(),"UTF-8"); 就是幫你把 ResponseEntity 這個實例的各項有用的值(以 UTF-8 的編碼)打印出來看,一個幫助方法而已。

2017年2月28日 04:30