Java从Apache IOUtils转换的字符串中获取InputStream
我正在使用库从Sharepoint下载文件。Java从Apache IOUtils转换的字符串中获取InputStream,java,apache-httpclient-4.x,ioutils,Java,Apache Httpclient 4.x,Ioutils,我正在使用库从Sharepoint下载文件。 我可以下载文件,但得到的是字符串格式,使用org.apache.commons.io.IOUtils转换为 public static String get(Pair<String, String> token, String url) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet getReque
我可以下载文件,但得到的是字符串格式,使用
org.apache.commons.io.IOUtils
转换为
public static String get(Pair<String, String> token, String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("Cookie", token.getLeft() + ";" + token.getRight());
getRequest.addHeader("accept", "application/json;odata=verbose");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() == 200) {
return IOUtils.toString(response.getEntity().getContent(), "utf-8");
} else {
System.err.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + ", " + url);
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException ex) {
Logger.getLogger(SPOnlineMFT.class).error(ex);
}
}
return null;
}
但我无法读取/打开文件,例如MS excel文件。打开文件时,收到的消息已损坏。只需将字节数组直接写入文件,而无需将其转换为utf-8字符串
import java.nio.file.Files;
import java.nio.file.Path;
Path file = Path.of("D:\\SharePoint\\TempDownload/"+fileName);
Files.write(file, response.getEntity().getContent()));
我必须返回,
response.getEntity().getContent()
给调用者,如果我在调用的方法中关闭了HttpClient
,内容将对我无效。然后只需在局部变量中保留对它的引用,您也可以返回给调用者。。。
import java.nio.file.Files;
import java.nio.file.Path;
Path file = Path.of("D:\\SharePoint\\TempDownload/"+fileName);
Files.write(file, response.getEntity().getContent()));