httpurlconnection下载excel文件
时间: 2024-01-28 11:04:30 浏览: 26
你可以使用以下代码使用 HttpURLConnection 下载 Excel 文件:
```java
URL url = new URL("http://www.example.com/sample.xls");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
// 设置请求头,如果服务器需要验证可以在此处设置用户名和密码
// conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString("username:password".getBytes(), Base64.NO_WRAP));
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream("sample.xls");
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("Excel file downloaded");
} else {
System.out.println("Server returned response code: " + responseCode);
}
```
这段代码会从指定 URL 下载 Excel 文件,并将其保存为 "sample.xls"。如果服务器需要验证,你可以在请求头中设置用户名和密码。注意,你需要将代码中的 URL 替换为你所需要下载的实际 URL。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)