不推荐使用Java HttpClient - 它有多难?

时间:2013-03-11 10:38:55

标签: java apache-httpclient-4.x apache-commons-httpclient

我要做的就是下载一些JSON并将其反序列化为一个对象。我还没有下载JSON。

我能找到的几乎所有HttpClient示例,包括apache站点上的那些看起来都像......

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

public void blah() {
    HttpClient client = new DefaultHttpClient();
    ...
}

然而,Netbeans告诉我DefaultHttpClient已被弃用。我已经尝试使用谷歌搜索DefaultHttpClient deprecated以及我能想到的许多其他变体,并且找不到任何有用的结果,所以我显然错过了一些东西。

下载网页内容的正确Java7方式是什么?作为语言的一部分,真的没有像样的Http客户端吗?我觉得很难相信。

My Maven对此的依赖是......

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>LATEST</version>
    <type>jar</type>
</dependency>

10 个答案:

答案 0 :(得分:245)

相关进口商品:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;

用法:

HttpClient httpClient = HttpClientBuilder.create().build();
编辑(在Jules的建议之后):

build()方法返回CloseableHttpClient AutoClosable时,您可以将声明放在try-with-resources语句中(Java 7 +):

try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

    // use httpClient (no need to close it explicitly)

} catch (IOException e) {

    // handle

}

答案 1 :(得分:56)

恕我直言,接受的答案是正确的,但是错过了一些“教学”。因为它没有解释如何提出答案。 对于所有已弃用的类,请查看JavaDoc(如果您没有下载它或go online),它将提示用于替换旧代码的类。当然它不会告诉你一切,但这是一个开始。例如:

...
 *
 * @deprecated (4.3) use {@link HttpClientBuilder}.  <----- THE HINT IS HERE !
 */
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {

现在你有了要使用的类,HttpClientBuilder,因为没有构造函数来获取构建器实例,你可能会猜测必须有一个静态方法:{{1} }。一旦你有了构建器,你也可以猜测,对于大多数构建器来说,有一个构建方法,因此:

create

<强> AutoClosable:

正如Jules在评论中暗示的那样,返回的类实现了org.apache.http.impl.client.HttpClientBuilder.create().build(); ,所以如果你使用Java 7或更高版本,你现在可以这样做:

java.io.Closable

优点是你不必处理finally和null。

其他相关信息

另请务必阅读connection pooling并设置timeouts

答案 2 :(得分:10)

Examples from Apache 使用此:

HttpClient httpclient = HttpClients.createDefault();

自版本4.3以来,班级org.apache.http.impl.client.HttpClients就在那里。 HttpClients.createDefault()的代码与此处接受的答案相同。

答案 3 :(得分:7)

由于4.3-alpha1版本规范,您在版本LATEST中已弃用。如果您查看该类的javadoc,它会告诉您要使用的内容:HttpClientBuilder

在最新的稳定版本(4.2.3)中,DefaultHttpClient尚未弃用。

答案 4 :(得分:7)

尝试jcabi-http,这是一个流畅的Java HTTP客户端,例如:

String html = new JdkRequest("https://www.google.com")
  .header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML)
  .fetch()
  .as(HttpResponse.class)
  .assertStatus(HttpURLConnection.HTTP_OK)
  .body();

另请参阅此博文:http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

答案 5 :(得分:3)

如果您只是尝试读取json数据,我建议使用以下方法。

URL requestUrl=new URL(url);
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
int cp;
try {
    while((cp=rd.read())!=-1){
    sb.append((char)cp);
  }
 catch(Exception e){
 }
 String json=sb.toString();

答案 6 :(得分:2)

您可以添加以下Maven依赖项。

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.1</version>
    </dependency>

您可以在java代码中使用以下导入。

import org.apache.http.HttpEntity;
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;

您可以在java代码中使用以下代码块。

HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new HttpGet("http://example.domain/someuri");

HttpResponse response = client.execute(httpUriRequest);
System.out.println("Response:"+response);

答案 7 :(得分:1)

使用HttpClientBuilder构建HttpClient,而不是使用DefaultHttpClient

例如:

MinimalHttpClient httpclient = new HttpClientBuilder().build();

 // Prepare a request object
 HttpGet httpget = new HttpGet("http://www.apache.org/");

答案 8 :(得分:1)

这是我已经应用于httpclient在此版本的android 22中弃用的问题的解决方案

 public static String getContenxtWeb(String urlS) {
    String pagina = "", devuelve = "";
    URL url;
    try {
        url = new URL(urlS);
        HttpURLConnection conexion = (HttpURLConnection) url
                .openConnection();
        conexion.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conexion.getInputStream()));
            String linea = reader.readLine();
            while (linea != null) {
                pagina += linea;
                linea = reader.readLine();
            }
            reader.close();

            devuelve = pagina;
        } else {
            conexion.disconnect();
            return null;
        }
        conexion.disconnect();
        return devuelve;
    } catch (Exception ex) {
        return devuelve;
    }
}

答案 9 :(得分:-2)

对于原始问题,我会要求您应用以下逻辑:

 CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 HttpPost httpPostRequest = new HttpPost();