不推荐使用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站点上的那些看起来像...... / p>
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已弃用
以及我能想到的许多其他变体,但找不到任何有用的结果,所以我显然遗漏了一些东西。
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.
My 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();
编辑(在Jules的建议之后):
EDIT (after Jules' suggestion):
当 build()
方法返回 CloseableHttpClient
其中是-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屋!