如何使用Google Drive REST AP和HTTPClient创建文件夹?

我正在使用带有HTTPClient的Google Drive REST API来创建文件夹。 REST API是这里的文档请注意REST AP请求执行 – 但使用了错误的数据:tt创建一个名为“untitled”的新文件并将我的json放在那里。

我已经尝试了使用HTTPClient构建POST请求的不同方法,这些方法成功执行 – 但不知何故,Google Drive响应创建文件并返回此数据并忽略我提交的POST数据。

这就是服务器所响应的内容
..

“kind”:“drive#file”,“id”:“0B-fYJN-c4UDjUlh1TUZadF9vejA”,这是一个有效的ID“title”:“Untitled”,—-错误的标题“mimeType”:“application / json; charset = UTF-8“, – 这是错误的mimeType ..

我尝试了以下调用API的方法:我不确定我发送的数据发生了什么。

1)使用表单名称值对

DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("https://www.googleapis.com/upload/drive/v2/files?key="+GoogleClientConstants.GOOGLE_api_key); postRequest.addHeader("Authorization", "Bearer " + accessToken); postRequest.addHeader("Content-Type", "application/json; charset=UTF-8"); List  nvps = new ArrayList (); nvps.add(new BasicNameValuePair("title", "vip")); nvps.add(new BasicNameValuePair("mimeType", "application/vnd.google-apps.folder")); postRequest.setEntity(new UrlEncodedFormEntity(nvps, org.apache.http.Consts.UTF_8 )); HttpResponse response = httpClient.execute(postRequest); 

2)使用StringEntity

 JSONObject jo= new JSONObject(); jo.element("title", "pets").element("mimeType", "application/vnd.google-apps.folder"); ContentType contentType= ContentType.create("application/json", Charset.forName("UTF-8")) ; StringEntity entity = new StringEntity(jo.toString(), contentType); logger.info(" sending "+ jo.toString()); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); 

在这两种情况下,Google API都会以200响应以及上面提到的FileResource。

我用你的代码创建了一个小例子。 对我来说一切正常。 请看我的源代码:

 import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import com.google.gson.JsonObject; public class SourceCodeProgram { public static void main(String argv[]) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost( "https://www.googleapis.com/drive/v2/files"); post.addHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Bearer XXXXXXXXXXXXXXXXXXXXXXXXX"); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("title", "Test folder"); jsonObject .addProperty("mimeType", "application/vnd.google-apps.folder"); post.setEntity(new StringEntity(jsonObject.toString())); httpClient.execute(post); } } 

上面的代码不会抛出任何exception。 我已经检查了我的驱动器,我可以在其中看到“测试文件夹”。 您在postURL中放置的关键是什么?

您为什么不在自己的应用中使用Google云端硬盘客户端库 ?

要创建子文件夹,您必须使用父文件夹的ID,例如在具有ID XXX的父文件夹“super”中创建文件夹“sub”:

 POST https://www.googleapis.com/drive/v2/files Authorization: Bearer {ACCESS_TOKEN} Content-Type: application/json ... { "title": "sub", "parents": [{"id":"XXX"}] "mimeType": "application/vnd.google-apps.folder" } 

要创建根文件夹,可以忽略“parents”参数