- 我在共享点上存储了一个 .xlsx 文件,需要登录才能获取/查看该 Excel 文件。
- 我需要该文件才能对其执行一些 ApachePOI 操作
- 如何下载该文件?
我尝试通过 InputStream 进行此操作,但我不知道如何进行身份验证,并且收到了 403 错误,这是显而易见的,因为我不提供密码/登录名(不知道如何提供)
InputStream inputStream = new URL("https://example.sharepoint.com/something/something1/file.xlsx").openStream();
Files.copy(inputStream, Paths.get("C:/file.xlsx"));
有没有一种简单的方法来访问该文件?
最佳答案
我会尝试将java.net.HttpURLConnection
与java.net.Authenticator
和java.net.PasswordAuthentication
一起使用。
示例:
import org.apache.poi.ss.usermodel.*;
import java.io.InputStream;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
class ReadExcelFromURL {
public static void main(String[] args) throws Exception {
Authenticator.setDefault (new Authenticator() {
private String username = "Domain\\UserName";
private String password = "password";
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (username, password.toCharArray());
}
});
String stringURL = "https://example.sharepoint.com/something/something1/file.xlsx";
URL url = new URL(stringURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
InputStream in = con.getInputStream();
Workbook workbook = WorkbookFactory.create(in);
for (Sheet sheet : workbook) {
System.out.println(sheet); // success?
}
workbook.close();
}
}
关于java - 如何访问 Apache POI 上存储在 Sharepoint(带身份验证)上的 .xlsx 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58626879/