URL.openStream() 和 respone.getEntity().getContent() 一样吗?
Is URL.openStream() the same as respone.getEntity().getContent()?
当我向特定 URL
发出 get
请求时,将下载一个文件。我可以通过两种方式获得 InputStream
。
方法一
在 java.net
包中使用 URL
class。
java.net.URL url = new URL(downloadFileUrl);
InputStream inputStream = url.openStream();
方法二
使用 Apache
的 HttpClient
class。
org.apache.http.impl.client.CloseableHttpClient httpclient = new CloseableHttpClient();
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute((HttpUriRequest)request);
InputStream inputStream = response.getEntity().getContent();
这些方法一样吗?如果不是怎么办?一般或在特定情况下首选哪种方法?
我提供的例子很简单。假设我做了必要的
使用 URL
和 HttpClient
对象进行配置以获得成功的响应。
两种方法returns 从连接读取输入流。这些方法之间没有区别。由于 HttpClient 是第三方库,您需要检查是否存在任何漏洞并不断更新库。
唯一的区别是 HttpClient 仅支持 HTTP(s) 协议,而 URLConnection 也可以用于其他协议,例如 FTP
在功能方面,Apache HttpClient 比 URLConnection 有更多的微调选项
当我向特定 URL
发出 get
请求时,将下载一个文件。我可以通过两种方式获得 InputStream
。
方法一
在 java.net
包中使用 URL
class。
java.net.URL url = new URL(downloadFileUrl);
InputStream inputStream = url.openStream();
方法二
使用 Apache
的 HttpClient
class。
org.apache.http.impl.client.CloseableHttpClient httpclient = new CloseableHttpClient();
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute((HttpUriRequest)request);
InputStream inputStream = response.getEntity().getContent();
这些方法一样吗?如果不是怎么办?一般或在特定情况下首选哪种方法?
我提供的例子很简单。假设我做了必要的
使用 URL
和 HttpClient
对象进行配置以获得成功的响应。
两种方法returns 从连接读取输入流。这些方法之间没有区别。由于 HttpClient 是第三方库,您需要检查是否存在任何漏洞并不断更新库。
唯一的区别是 HttpClient 仅支持 HTTP(s) 协议,而 URLConnection 也可以用于其他协议,例如 FTP
在功能方面,Apache HttpClient 比 URLConnection 有更多的微调选项