【问题标题】:Why I am getting DefaultHttpClient is deprecated?为什么我得到 DefaultHttpClient 已被弃用?
【发布时间】:2014-07-16 18:54:57
【问题描述】:

我正在做一个项目,我需要调用我的服务,我的服务将以 JSON 格式返回数据。而且我不需要将这个 JSON 响应序列化到任何 POJO,我只需要将数据作为 String 取回。而且这个应用程序对性能非常关键,所以HttpClient 必须非常快

所以我决定使用 Apache HttpClient 还是有更好的替代方案可以使用?

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("some-url");
request.addHeader("Context", "some-value");
HttpResponse response = httpClient.execute(request);
String response =  IOUtils.toString(response.getEntity().getContent(), "UTF-8");

但它抱怨The type DefaultHttpClient is deprecated,所以也许他们有新版本的HttpClient 或其他方式对 URL 进行 HttpClient 调用?

我有什么遗漏吗?

【问题讨论】:

标签: java httpclient


【解决方案1】:

使用这个:

HttpClient httpclient = HttpClientBuilder.create().build();

参考这个stackoverflow post

【讨论】:

    【解决方案2】:

    从 Apache HTTP Client API 版本 4.3 起,DefaultHttpClient 已被弃用。

    以下面的maven依赖为例。

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    

    导入后。

    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGett;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.client.methods.HttpUriRequest;
    

    以下代码块。

    HttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest httpUriRequest = new 
    HttpGet("http://example.domain/someuri");
    
    HttpResponse response = client.execute(httpUriRequest);
    System.out.println("Response:"+response);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2012-10-09
      相关资源
      最近更新 更多