Google Documents List API 文件上传 400 响应 [英] Google Documents List API file upload 400 response

查看:28
本文介绍了Google Documents List API 文件上传 400 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Android 编写自己的 Google Drive 客户端实现,并且我正在使用文档列表 API.最近我遇到了以下问题:

I am writing my own implementation of the Google Drive client for the Android and I am using the docs list api. Recently I've encountered a following problem:

起初我使用 HttpURLConnection 上传文件,但它似乎在调用 getResponseCose() 后将数据写入套接字,而不是在我写入连接的 OutputStream 时,这对我来说是必须的.

然后我切换到 Apache HttpClient 但我仍然收到 400 响应,不知道为什么.也许你能帮助我.这是用于上传文件的代码.


At first I was using the HttpURLConnection to upload the file but it seems like it writes the data to the socket after a call to getResponseCose(), not when I am writing to the connection's OutputStream, which is a must for me.

Then I've switched to the Apache HttpClient but I'm still getting a 400 response, not sure why. Maybe you will be able to help me. Here is the code used to upload a file.


String putUrl = conn.getHeaderField("Location");//from the previous request
final HttpClient client = new DefaultHttpClient();
final HttpPut put = new HttpPut(putUrl);

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
put.addHeader("Content-Type", mime==null?"file":mime);
//put.addHeader("Content-Length", String.valueOf(length));
put.addHeader("Content-Range", "bytes 0-"+(length-1)+"/"+length);
put.addHeader("GData-Version", "3.0");
put.addHeader("Authorization", getAuthorizationProperty());
entity.addPart("content", new InputStreamBody(in, name));
put.setEntity(entity);

HttpResponse resp = client.execute(put);
int response = resp.getStatusLine().getStatusCode();
if(response == HttpStatus.SC_CREATED){
    lastCreated = parseSingleXMLEntry(resp.getEntity().getContent());
}

完全相同的头文件适用于 HttpURLConnection.也许实体是错的?

Exactly the same headers worked for HttpURLConnection. Maybe the entity is wrong?

推荐答案

好的,解决方法很简单,希望对大家有用.

Ok, the solution is quite simple, hope it will be useful for someone.

我必须删除所有向请求添加标头的行.之后,我将 mime 类型添加到 InputStreamBody 构造函数并覆盖 getContentLength() 方法以提供流长度.最后看起来像这样:

I had to delete all lines which added headers to the request. After that I've added the mime type to the InputStreamBody constructor and overriden the getContentLength() method to provide stream length. Finally it looks like this:

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("content", new InputStreamBody(in, ,mime, name){
     @Override
     public long getContentLength() {
          return length;
     }
});
put.setEntity(entity);

HttpResponse resp = client.execute(put);

仅此而已.

这篇关于Google Documents List API 文件上传 400 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆