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

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

问题描述

我正在为Android编写自己的Google Drive客户端实现,并且正在使用docs list 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天全站免登陆