欢迎光临
我们一直在努力

DefaultHttpClient显示被弃用解决办法

DefaultHttpClient被弃用可以用HttpClient来代替。注:HttpClient不是java.net.http里面的那个,而是org.apach.http.client.HttpClient。

DefaultHttpClient代码

@GetMapping("/test/testGet")
public String testGet() throws IOException {
    DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
    HttpGet httpGet = new HttpGet("http://localhost:7500/pfc/dict/bounceType");
    httpGet.setHeader("Content-Type", "application/json");
    CloseableHttpResponse response = client.execute(httpGet);
    HttpEntity httpEntity = response.getEntity();
    String result = EntityUtils.toString(httpEntity, "UTF-8");
    return  result;
}

HttpClient代码

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

...

@GetMapping("/test/testGet")
public String testGet() throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet httpGet = new HttpGet("http://localhost:7500/pfc/dict/bounceType");
    httpGet.setHeader("Content-Type", "application/json");
    HttpResponse response = client.execute(httpGet);
    HttpEntity httpEntity = response.getEntity();
    String result = EntityUtils.toString(httpEntity, "UTF-8");
    return  result;
}

代码HttpClientBuilder.create().build()的返回类型其实是CloseableHttpClient,但是因为CloseableHttpClient继承于HttpClient,所以这里用HttpClient接收也没有问题。

还有就是执行请求得到远程响应类型为HttpResponse而不是CloseableHttpResponse

CloseableHttpResponse closeableHttpResponse = (CloseableHttpResponse) client.execute(request);
赞(1)
版权归原作者所有,如有侵权请告知。达维营-前端网 » DefaultHttpClient显示被弃用解决办法

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址