我正在开发一个需要向 Google 驱动器创建一个新的空文件(不是文档)的功能,现在我使用的是文档列表 API 3.0,我指的是文档:https ://developers.google.com/google-apps /documents-list/#uploading_a_new_document_or_file_with_both_metadata_and_content。我会将一个零字节文件上传到 Google 驱动器以生成空文件。
现在我在请求步骤 1 和请求步骤 2 中遇到问题。在第一个 Post[resumable-create-media link] 请求之后,我成功获得了上传位置。然后,当我向该位置请求 put 方法时,出现 404 not found 错误。所有请求都有“GData-Version: 3.0”和“Authorization: accessToken”标头。
我从论坛中搜索了很多,并弄清楚如何创建空文档,但无法弄清楚如何创建空文件。这是我的代码,有人可以帮忙看看哪一部分是错的吗?提前致谢。
private final static String PARAM_CONTENT_TYPE = "Content-Type";
private final static String PARAM_UPLOAD_LENGTH = "X-Upload-Content-Length";
private final static String PARAM_UPLOAD_TYPE = "X-Upload-Content-Type";
private final static String CONTENT_TYPE_XML = "application/atom+xml";
private final static String URI_RESUMABLE_RESOURCE = "https://docs.google.com/feeds/upload/create-session/default/private/full";
private final static String ENTITY_NEW_FILE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" "
+ "xmlns:docs=\"http://schemas.google.com/docs/2007\"><title>{0}</title></entry>";
@Override
public boolean createNewFile() throws IOException {
String uri = null;
if (ROOT.equals(parentResourceId))
uri = URI_RESUMABLE_RESOURCE;
else
uri = URI_RESUMABLE_RESOURCE + "/%3A" + parentResourceId + "/contents";
try {
StringEntity entity = new StringEntity(MessageFormat.format(ENTITY_NEW_FILE, getName()), Constants.ENCODING);
Map<String, String> headers = new HashMap<String, String>();
headers.put(PARAM_CONTENT_TYPE, CONTENT_TYPE_XML);
headers.put(PARAM_UPLOAD_LENGTH, "0");
headers.put(PARAM_UPLOAD_TYPE, "text/plain");
Map<String, String> params = new HashMap<String, String>();
params.put("convert", "false");
HttpResponse response = helper.execMethodAsResponse(uri, new PostMethod(entity), headers, params);
String location = null;
if ((location = response.getFirstHeader("Location").getValue()) != null) {
headers = new HashMap<String, String>();
headers.put(PARAM_CONTENT_TYPE, "text/plain");
headers.put("Content-Range", "bytes 0-0/0");
//FIXME: Problem occurs here, this put invocation will return 404 not found error.
JsonObject obj = helper.execMethodAsJson(location, new PutMethod(new ByteArrayEntity(new byte[0])), headers, null);
if (obj != null) {
decorateFile(this, obj.get("entry").getAsJsonObject());
return true;
}
}
} catch (UnsupportedEncodingException e) {
}
return false;
}