Google Drive API - 仅更新文件元数据
我正在尝试重命名Google Drive文件资源。我想我只是错过了一些东西,因为所有其他的行为,如获取文件列表,插入文件,在目录之间移动文件正在工作。Google Drive API - 仅更新文件元数据
先决条件:尝试使用此文档重命名文件资源https://developers.google.com/drive/v2/reference/files/update与java(只有JDK的东西)。另外,我不使用gdrive java sdk,apache http客户端或其他库...只需清理JDK工具。
所以我做什么:
Here是我想发送的文件的元数据。
修改元数据
-
这里
title
属性代码:URLConnection urlConnection = new URL("https://www.googleapis.com/drive/v2/files/" + fileId).openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setRequestMethod("PUT"); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestProperty("Authorization", "Bearer " + accessToken); DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream()); outputStream.writeBytes(FILE_RESOURCE_METADATA_WITH_CHANGED_TITLE_IN_JSON); outputStream.flush(); outputStream.close(); }
使实际调用API后,我收到响应主体200状态码和文件资源(如预期)但标题保持不变。所以我没有错误没有改变标题。
此外,谷歌驱动器API会忽略文件资源的任何变化。它只是返回相同的文件资源,没有应用任何更改(尝试使用标题,说明,originalFileName,父项属性)。
我也试过到目前为止:
-
仅发送应该改变的属性,如
{"title":"some_new_name"}
结果是一样的。
将
PUT
更改为PATCH
。不幸的是,HttpURLConnection不支持PATCH
,但解决方法给出了相同的结果。更改将被忽略。使用谷歌api exlorer(它可以在API参考页面的右侧找到) - 和...它的工作原理。只填充请求正文中的fileId和title属性,它工作。文件被重命名。
我错过了什么?
尝试documentation中给出的示例java代码。
由于代码涉及更新现有文件的元数据和内容。
从代码,你会发现file.setTitle(newTitle)
我认为你想要实现的一个。
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import java.io.IOException;
// ...
public class MyClass {
// ...
/**
* Update an existing file's metadata and content.
*
* @param service Drive API service instance.
* @param fileId ID of the file to update.
* @param newTitle New title for the file.
* @param newDescription New description for the file.
* @param newMimeType New MIME type for the file.
* @param newFilename Filename of the new content to upload.
* @param newRevision Whether or not to create a new revision for this
* file.
* @return Updated file metadata if successful, {@code null} otherwise.
*/
private static File updateFile(Drive service, String fileId, String newTitle,
String newDescription, String newMimeType, String newFilename, boolean newRevision) {
try {
// First retrieve the file from the API.
File file = service.files().get(fileId).execute();
// File's new metadata.
file.setTitle(newTitle);
file.setDescription(newDescription);
file.setMimeType(newMimeType);
// File's new content.
java.io.File fileContent = new java.io.File(newFilename);
FileContent mediaContent = new FileContent(newMimeType, fileContent);
// Send the request to the API.
File updatedFile = service.files().update(fileId, file, mediaContent).execute();
return updatedFile;
} catch (IOException e) {
System.out.println("An error occurred: " + e);
return null;
}
}
// ...
}
希望这给你一点。
找到解决方案...
添加此请求属性解决了问题。
httpURLConnection.setRequestProperty("Content-Type", "application/json")