2017-09-01 117 views
1

我正在使用Restful API開發Google Drive API。使用JSON對Java多部分文件進行上傳

我需要上傳文件和json正文。

但是,當我嘗試上傳與我的java代碼,我遇到了谷歌驅動器的錯誤代碼。

==>無效多跟0 MIME部分

請求這裏是谷歌驅動器的導向件。 enter image description here

這是我的代碼。 我的代碼有什麼問題?

public int uploadFileToGoogleDrive(File file, Long acctId, String 
accessToken, JSONObject json) { 
    HttpClient httpClient = new HttpClient(); 
    PostMethod method = null; 
    Integer result = -1; 
    String boundary = "---------------------------" + System.currentTimeMillis(); 
    try { 
     method = new PostMethod("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"); 
     method.setRequestHeader("Authorization", "Bearer " + accessToken); 
     method.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary); 

     Part[] parts = {new StringPart("",json.toString(),"utf-8"), new FilePart(file.getName(), file, null, "utf-8")}; 

     //MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams()); 
     method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); 

     httpClient.getHttpConnectionManager().closeIdleConnections(0); 
     result = httpClient.executeMethod(method); 

     if (result == HttpStatus.SC_OK) { 
      InputStream rstream = null; 
      rstream = method.getResponseBodyAsStream(); 
      BufferedReader br = new BufferedReader(
        new InputStreamReader(rstream)); 
      String line; 
      while ((line = br.readLine()) != null) { 
       resultString += line; 
      } 
     } 
     System.out.println("##############################################\n" + json.toString() + "\n##############################################"); 
     logger.debug(resultString); 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     logger.error(e.getMessage(), e); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     logger.error(e.getMessage(), e); 
    } 
    catch (ProtocolException e) { 
     // TODO Auto-generated catch block 
     logger.error(e.getMessage(), e); 
    } 
    catch (IOException e) { 
     // TODO Auto-generated catch block 
     logger.error(e.getMessage(), e); 
    }finally { 
     method.releaseConnection(); 
    } 
    return result; 
} 

}

回答

0

多形式上傳工作得很好。只是不要指定一個自定義 內容類型。否則您的內容類型將失敗,因爲 表單數據邊界由XHR庫在內部確定。如果您 要使用你的內容類型,那麼你將不得不單獨構建你 請求,並在「原始」方式粘貼文本

看看this discussiointhis one