Google云端分段上传

时间:2014-10-03 10:48:53

标签: java httpclient google-drive-api

我正在使用https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart上传文件元数据信息。我正在使用它上传代码

HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart");

String accessToken="ya29.kwDKqMocFOkP5jF7gRugZGebVDErW4toL-11i_SPO8wDam3X7GTNCEXL";
post.setHeader("Content-Type","multipart/related; boundary=foo_bar_baz");
post.addHeader("Authorization","Bearer "+accessToken);String value="--foo_bar_baz
Content-Type:application/json charset=UTF-8";
String hello="ddddddddddddddd";
StringEntity str=new StringEntity(value+"\n"+object.toString()+"\n--foo_bar_baz \n Content-Type:plain/text \n"+hello+"\n \n--foo_bar_baz-- ","UTF-8");
post.setEntity(str);
HttpResponse response = client.execute(post);

但是我的反应是多方形的身体。请帮助我解决这个问题。

由于

1 个答案:

答案 0 :(得分:0)

String accessToken="ya29.kwDKqMocFOkP5jF7gRugZGebVDErW4toL-11i_SPO8wDam3X7GTNCEXL";
HttpPost httpPost = new HttpPost("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart");
httpPost.addHeader("Authorization", "Bearer "+accessToken);
httpPost.setHeader("Content-Type","multipart/related; boundary=foo_bar_baz");

JSONObject json = new JSONObject();
json.put("title", "NewFile.txt"); // {'title': 'My File.txt'}

String fileContent = "This is in the file";

StringEntity str=new StringEntity("--foo_bar_baz\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n\n"+json.toString()+"\r\n--foo_bar_baz\r\nContent-Type: plain/text\r\n\r\n"+fileContent+"\r\n--foo_bar_baz--");
httpPost.setEntity(str);

CloseableHttpResponse response = new DefaultHttpClient().execute(httpPost);
String jsonResponse = EntityUtils.toString(response.getEntity());
response.close();
System.out.println("jsonResponse:"+jsonResponse);