2013-07-15 68 views
0

我正在嘗試使用Jersey 2.0爲Google Drive實現REST客戶端。Google Drive API上的文件上傳失敗

根據以下文件,我製作了通過多部分請求發送文件的代碼。

https://developers.google.com/drive/v2/reference/files/insert https://developers.google.com/drive/manage-uploads

String targetUrl = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&access_token=" + token.access_token; 
    WebTarget target = client.target(targetUrl); 
    final FileDataBodyPart filePart = new FileDataBodyPart("file", file); 
    final MultiPart multipart = new FormDataMultiPart().field("title", file.getName()) 
     .field("description", file.getName()) 
     .bodyPart(filePart); 
    Response response = target.request(MediaType.APPLICATION_JSON_TYPE) 
      .post(Entity.entity(multipart, multipart.getMediaType())); 
    System.out.println("response:" + response.readEntity(String.class)); 

下面是由代碼中的POST請求。

POST /upload/drive/v2/files?uploadType=multipart&access_token={ACCESS_TOKEN} HTTP/1.1\r\n 
Accept: application/json\r\n 
Content-Type: multipart/form-data; boundary=Boundary_1_1833261898_1373877178038\r\n 
User-Agent: Jersey/2.0 (HttpUrlConnection 1.7.0_25)\r\n 
MIME-Version: 1.0\r\n 
Host: www.googleapis.com\r\n 
Content-Length: 42430\r\n 

MIME Multipart Media Encapsulation, Type: multipart/form-data, Boundary: "Boundary_1_1833261898_1373877178038" 
Type: multipart/form-data 
First boundary: --Boundary_1_1833261898_1373877178038\r\n 
Encapsulated multipart part: (text/plain) 
    Content-Type: text/plain\r\n 
    Content-Disposition: form-data; name="title"\r\n\r\n 
    Line-based text data: text/plain 
Boundary: \r\n--Boundary_1_1833261898_1373877178038\r\n 
Encapsulated multipart part: (text/plain) 
    Content-Type: text/plain\r\n 
    Content-Disposition: form-data; name="description"\r\n\r\n 
    Line-based text data: text/plain 
Boundary: \r\n--Boundary_1_1833261898_1373877178038\r\n 
Encapsulated multipart part: (text/plain) 
    Content-Type: text/plain\r\n 
    Content-Disposition: form-data; filename="GoogleDrive.txt"; modification-date="Fri, 12 Jul 2013 08:15:47 GMT"; size=41918; name="file"\r\n\r\n 
    Line-based text data: text/plain 
Last boundary: \r\n--Boundary_1_1833261898_1373877178038--\r\n 

我的帖子請求已發送,但發生了以下錯誤。

{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "parseError", 
    "message": "Parse Error" 
    } 
    ], 
    "code": 400, 
    "message": "Parse Error" 
} 
} 

請告訴我如何避免這個錯誤。

回答

0

上傳請求應該有兩個多部分:元數據和文件內容和元數據部分應該是JSON。

在你的情況下,你爲每個屬性創建一個新的表單編碼部分。使用上文檔的參考看到正確的格式:https://developers.google.com/drive/manage-uploads#multipart

final MultiPart multipart = new FormDataMultiPart().field("title", file.getName()) 
    .field("description", file.getName()) 
    .bodyPart(filePart); 

你多域主體應該是有效的JSON。

+0

感謝您的回覆,Dogan。 正如您所說,我修改了代碼並確認我的代碼正常工作,並且可以向Google雲端硬盤發送文件。 非常感謝你的確。 – moomindani

相關問題