Google api Google Drive API-仅更新文件元数据
我正在尝试重命名谷歌驱动器文件资源。我想我只是错过了一些东西,因为所有其他的操作,比如获取文件列表、插入文件、在目录之间移动文件都在工作 先决条件:使用java(仅使用JDK)尝试使用此文档重命名文件资源。此外,我不使用gdrive java sdk、apache http客户端或其他库。。。只需清理JDK工具 所以我要做的是:Google api Google Drive API-仅更新文件元数据,google-api,google-drive-api,google-apis-explorer,Google Api,Google Drive Api,Google Apis Explorer,我正在尝试重命名谷歌驱动器文件资源。我想我只是错过了一些东西,因为所有其他的操作,比如获取文件列表、插入文件、在目录之间移动文件都在工作 先决条件:使用java(仅使用JDK)尝试使用此文档重命名文件资源。此外,我不使用gdrive java sdk、apache http客户端或其他库。。。只需清理JDK工具 所以我要做的是: 是我试图发送的文件元数据 修改此元数据中的title属性 代码如下: URLConnection urlConnection = new URL("https://ww
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();
}
{"title":"some_new_name"}
PUT
更改为PATCH
。不幸的是,补丁
不受HttpURLConnection支持,但解决方法给出了相同的结果。更改将被忽略我缺少什么?请尝试中给出的示例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")