最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Java Microsoft Graph API: "Specified HTTP method is not allowed for the request target" when creating Upload S

programmeradmin5浏览0评论

I am working on a Java application that interacts with Microsoft Graph API to upload files to OneDrive. As part of the upload process, I need to create an Upload Session using the API. However, I am encountering the following error: Error Details:

java.lang.RuntimeException: Failed to create upload session: {"error":{"code":"Request_BadRequest","message":"Specified HTTP method is not allowed for the request target.","innerError":{"date":"2025-01-18T09:08:51","request-id":"965e3bdd-7ba4-4c94-8f03-94e5473ef692","client-request-id":"965e3bdd-7ba4-4c94-8f03-94e5473ef692"}}}

Here is the method I use to create the upload session:

public String createUploadSession(String userId, String fileName) throws Exception {
    String url = ".0/users/" + userId + "/drive/root:/" + fileName + ":/createUploadSession";
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("PUT"); // Should this be PUT or another method like POST?
    connection.setRequestProperty("Authorization", "Bearer " + accessToken);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);

    // Send JSON payload
    String jsonPayload = "{\"item\": {\"@microsoft.graph.conflictBehavior\": \"rename\"}}";
    try (OutputStream os = connection.getOutputStream()) {
        os.write(jsonPayload.getBytes());
    }

    // Check response
    if (connection.getResponseCode() == 200) {
        String response = new String(connection.getInputStream().readAllBytes());
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(response);
        return jsonNode.get("uploadUrl").asText(); // Extract `uploadUrl`
    } else {
        String error = new String(connection.getErrorStream().readAllBytes());
        throw new RuntimeException("Failed to create upload session: " + error);
    }
}

And this is how I call the method:

String fileName = "uploaded_video.mp4";
String userId = "tranduongtruong1623_gmail#EXT#@tranduongtruong1623gmail.onmicrosoft";

OneDriveService service = new OneDriveService();
service.createUploadSession(userId, fileName);


And finally, I also want to upload an MP4 file to OneDrive. Do you have any guide?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论