0

我正在为 Android 编写自己的 Google Drive 客户端实现,并且正在使用 docs list api。最近我遇到了以下问题:

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

然后我切换到 Apache HttpClient 但我仍然收到 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。也许实体是错误的?

4

1 回答 1

0

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

我不得不删除向请求添加标题的所有行。之后,我将 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);

就这样。

于 2012-06-25T15:32:27.013 回答