已弃用的 Java HttpClient - 有多难? [英] Deprecated Java HttpClient - How hard can it be?
问题描述
我要做的就是下载一些 JSON 并将其反序列化为一个对象.我还没有下载 JSON.
All I'm trying to do is download some JSON and deserialize it into an object. I haven't got as far as downloading the JSON yet.
我能找到的几乎每一个 HttpClient 示例,包括 apache 站点上的那些看起来像......
Almost every single HttpClient example I can find, including those on the apache site looks something like...
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
public void blah() {
HttpClient client = new DefaultHttpClient();
...
}
但是,Netbeans 告诉我 DefaultHttpClient
已被弃用.我已经尝试在谷歌上搜索 DefaultHttpClient deprecated
以及我能想到的尽可能多的其他变体,但找不到任何有用的结果,所以我显然遗漏了一些东西.
However, Netbeans tells me that DefaultHttpClient
is deprecated. I've tried googling for DefaultHttpClient deprecated
and as many other variations as I can think of and can't find any useful results, so I'm obviously missing something.
Java7 下载网页内容的正确方法是什么?作为语言的一部分,真的没有像样的 Http Client 吗?我觉得这很难相信.
What is the correct Java7 way to download the contents of a webpage? Is there really no decent Http Client as part of the language? I find that hard to believe.
我对此的 Maven 依赖是...
My Maven dependency for this is...
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>LATEST</version>
<type>jar</type>
</dependency>
推荐答案
相关导入:
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
用法:
HttpClient httpClient = HttpClientBuilder.create().build();
编辑(根据朱尔斯的建议):
EDIT (after Jules' suggestion):
由于 build()
方法返回一个 CloseableHttpClient
is-a AutoClosable
,您可以将try-with-resources 语句中的声明(Java 7+):
As the build()
method returns a CloseableHttpClient
which is-a AutoClosable
, you can place the declaration in a try-with-resources statement (Java 7+):
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
// use httpClient (no need to close it explicitly)
} catch (IOException e) {
// handle
}
这篇关于已弃用的 Java HttpClient - 有多难?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!