DefaultHttpClient已經被標注為deprecated,使用CloseableHttpClient代替怎么寫?。?/h1>
public?static?JSONObject?doGetStr(String?url)?{
????CloseableHttpClient?httpClient?=?HttpClientBuilder.create().build();
????HttpGet?httpGet?=?new?HttpGet(url);
????JSONObject?jsonObject?=?null;
????try?{
????????HttpResponse?response?=?httpClient.execute(httpGet);
????????HttpEntity?entity?=?response.getEntity();
????????if?(entity?!=?null)?{
????????????String?result?=?EntityUtils.toString(entity,?"UTF-8");
????????????jsonObject?=?JSONObject.fromObject(response);
????????}
????}?catch?(IOException?e)?{
????????e.printStackTrace();
????}
????return?jsonObject;
}我這么寫得到的entity根本不是想要的
public?static?JSONObject?doGetStr(String?url)?{
????CloseableHttpClient?httpClient?=?HttpClientBuilder.create().build();
????HttpGet?httpGet?=?new?HttpGet(url);
????JSONObject?jsonObject?=?null;
????try?{
????????HttpResponse?response?=?httpClient.execute(httpGet);
????????HttpEntity?entity?=?response.getEntity();
????????if?(entity?!=?null)?{
????????????String?result?=?EntityUtils.toString(entity,?"UTF-8");
????????????jsonObject?=?JSONObject.fromObject(response);
????????}
????}?catch?(IOException?e)?{
????????e.printStackTrace();
????}
????return?jsonObject;
}我這么寫得到的entity根本不是想要的
2017-02-22
第11行:
jsonObject?=?JSONObject.fromObject(result);????// 這里照著IDEA的提示按快了
另外,第7行替換為:
CloseableHttpResponse response = httpClient.execute(httpGet);
這個是官網示例的用法。小伙伴們如果遇到deprecated可以使用CloseableHttpClient替換。