我需要将文件上传到 SharePoint 中的自定义网站列表。我根据以下 URL 使用了 graph Rest API。
https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http
但是当我上传文件时出现以下错误。
HTTP response: {
"error": {
"code": "BadRequest",
"message": "Resource not found for the segment 'FileB.txt'.",
"innerError": {
"request-id": "30ccddb7-17b2-4b60-9943-39ce65eb301f",
"date": "2020-05-18T13:57:36"
}
}
}
这是我的示例 java 代码。
public void uploadFilesToList() throws MalformedURLException, IOException{
String tenantId = "48e2d3d3-5602-4db8-b9e4-xxxxxxxxxxxx";
String clientId = "f08b652a-6e3c-448f-b98c-xxxxxxxxxxxx";
String clientSecret = "KHII03L.77f6IP2zCm~v~hUXD.a.xxxxx";
clientSecret=java.net.URLEncoder.encode(clientSecret,"UTF-8");
String access_token = getaccetAuth(tenantId, clientId, clientSecret);
String siteId = "xxxxxxxx.sharepoint.com,ce2ae416-288b-41d4-8d58-af491571867a,976efac4-37b3-4515-858a-cdfddc936a39";
String listId = "8c47c9c5-88cb-4ad9-a94a-57b6dceec2a4";
String formattedUrl = String.format("https://graph.microsoft.com/v1.0/sites/%s/lists/%s/%s/content",
siteId,listId,"FileB.txt");
HttpPut put = null;
try {
File file = new File(("C:\\Users\\user_name\\Desktop"+"\\FileB.txt"));
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file));
HttpClient client = HttpClientBuilder.create().build();
put = new HttpPut(formattedUrl);
// add header
put.setHeader("Content-Type", "text/plain");
put.setHeader("Authorization", "Bearer " + access_token);
put.setEntity(entity);
HttpResponse response = client.execute(put);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
System.out.println("HTTP response: "+response.toString());
String json = EntityUtils.toString(response.getEntity());
System.out.println("HTTP response: "+json);
} finally {
put.releaseConnection();
}
}
这是我的获取 auth_token 方法。
public String getaccetAuth(String tnID, String clId, String cliSec) throws IOException {
String endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token",tnID);
String postBody = String.format("grant_type=password&client_id=%s&client_secret=%s&resource=%s&userName=%s&passWord=%s&scope=%s",
clId, cliSec, "https://graph.microsoft.com","admin@xxxxxx.onmicrosoft.com","xxxxxxx","https://graph.microsoft.com/.default");
HttpsURLConnection conn = (HttpsURLConnection) new URL(endpoint).openConnection();
conn.setRequestMethod("POST");
conn.addRequestProperty("Content_Type","application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.getOutputStream().write(postBody.getBytes());
conn.connect();
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(conn.getInputStream());
String accessToken = null;
while (parser.nextToken() != JsonToken.END_OBJECT) {
String name = parser.getCurrentName();
if ("access_token".equals(name)) {
parser.nextToken();
accessToken = parser.getText();
}
}
return accessToken;
}
我不确定这里出了什么问题。任何人都可以找到解决此问题的方法吗?注意:我在这里使用了硬编码值。