httpurlconnection下载excel文件并响应状态码
时间: 2024-01-28 07:04:30 浏览: 60
下面是使用 Java 中的 HttpURLConnection 类下载 Excel 文件并响应状态码的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadExcel {
public static void main(String[] args) throws IOException {
String fileUrl = "http://example.com/example.xls";
String saveDir = "C:\\Downloads\\";
String fileName = "example.xls";
URL url = new URL(fileUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(saveDir + fileName);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
System.out.println("Excel file downloaded successfully.");
} else {
System.out.println("Error downloading Excel file. Response code: " + responseCode);
}
}
}
```
在上面的示例代码中,我们首先定义了要下载的 Excel 文件的 URL、保存目录和文件名。然后,我们创建一个 URL 对象并打开一个 HttpURLConnection 连接。接下来,我们使用 HttpURLConnection.getResponseCode() 方法获取响应状态码。如果状态码为 `HTTP_OK`,则表示下载成功,我们使用 BufferedInputStream 和 FileOutputStream 将 Excel 文件写入指定的目录。最后,我们关闭了所有连接和流,并输出一条成功消息。如果状态码不是 `HTTP_OK`,则表示下载失败,并输出错误消息。
请注意,在实际开发中,您需要根据您的具体需求进行适当的修改。例如,您可能需要处理连接超时、读取超时、重定向等其他情况。
阅读全文