java 获取 http返回的文件流
时间: 2023-10-13 15:04:29 浏览: 38
好的,您需要使用 Java 中的 HttpGet 方法来进行 GET 请求,并获取返回的文件流。下面是一个简单的示例代码:
```
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://example.com/file");
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
InputStream inputStream = response.getEntity().getContent();
// 将文件流保存到本地文件中
FileOutputStream outputStream = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
// 关闭连接
EntityUtils.consume(response.getEntity());
response.close();
httpClient.close();
}
}
```
在这个示例中,我们使用了 Apache 的 HttpComponents 库来发送 GET 请求。首先我们创建了一个 CloseableHttpClient 对象,然后使用 HttpGet 方法来指定请求的 URL。接下来我们发送请求并获取响应,从响应中获取文件流。最后我们将文件流保存到本地文件中,并关闭连接。