Java 谷歌文档列表API文件上传400响应

Java 谷歌文档列表API文件上传400响应,java,google-docs-api,apache-httpclient-4.x,Java,Google Docs Api,Apache Httpclient 4.x,我正在为Android编写我自己的GoogleDrive客户端实现,我正在使用DocsList api。最近我遇到了以下问题: 起初,我使用HttpURLConnection上载文件,但它似乎在调用GetResponseCode()后将数据写入套接字,而不是在我写入连接的OutputStream时,这对我来说是必须的。 然后我切换到ApacheHttpClient,但仍然得到400响应,不知道为什么。也许你能帮助我。下面是用于上载文件的代码。 String putUrl = conn.getH

我正在为Android编写我自己的GoogleDrive客户端实现,我正在使用DocsList api。最近我遇到了以下问题:

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

然后我切换到ApacheHttpClient,但仍然得到400响应,不知道为什么。也许你能帮助我。下面是用于上载文件的代码。


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使用的标题完全相同。也许实体是错的?

好的,解决方案很简单,希望对其他人有用

我必须删除所有在请求中添加标题的行。之后,我将mime类型添加到InputStreamBody构造函数中,并重写getContentLength()方法以提供流长度。最后看起来是这样的:

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);
就这些