使用HTTP PUT上传Android文件

4
我有一个需要通过PUT请求向HTTP URL发送文件数据的Web服务。我知道如何做到这一点,但在Android上我不知道该怎么做。
API文档提供了一个示例请求。
PUT /images/upload/image_title HTTP/1.1
Host: some.domain.com
Date: Thu, 17 Jul 2008 14:56:34 GMT
X-SE-Client: test-account
X-SE-Accept: xml
X-SE-Auth: 90a6d325e982f764f86a7e248edf6a660d4ee833

bytes data goes here

我写了一些代码,但它出错了。
HttpClient httpclient = new DefaultHttpClient();
HttpPut request = new HttpPut(Host + "images/upload/" + Name + "/");
request.addHeader("Date", now);
request.addHeader("X-SE-Client", X_SE_Client);
request.addHeader("X-SE-Accept", X_SE_Accept);
request.addHeader("X-SE-Auth", Token);
request.addHeader("X-SE-User", X_SE_User);

// I feel here is something wrong
File f = new File(Path);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("photo", new FileBody(f));
request.setEntity(entity);

HttpResponse response = httpclient.execute(request);

HttpEntity resEntityGet = response.getEntity();

String res = EntityUtils.toString(resEntityGet); 

我是不是做错了什么?

这段文字涉及IT技术方面内容。
2个回答

5

尝试类似以下的操作

try {
URL url = new URL(Host + "images/upload/" + Name + "/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
    // etc.

    } catch (Exception e) { //handle the exception !}

编辑 - 另一个更好的选择:

建议使用内置的HttpPut - 示例请参见http://massapi.com/class/org/apache/http/client/methods/HttpPut.java.html

编辑2 - 根据评论要求:

在调用execute之前,使用setEntity方法并将new FileEntity(new File(Path), "binary/octet-stream")作为参数添加到PUT请求中以添加文件。


我们该如何将这些图像字节数据放入 PUT 请求中?我需要把它放到实体中,然后再将实体放到 PUT 请求中吗? - Umair A.
@Yahia,你的第一次编辑是我目前找到的最好的解决方案。 - osayilgan
如何将头部添加到put方法? - KarnakerReddy Gaddampally

4
以下代码对我来说运行良好:
URI uri = new URI(url);
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);

File file = new File(filename);         

MultipartEntity entity = new MultipartEntity();
ContentBody body = new FileBody(file, "image/jpeg");
entity.addPart("userfile", body);

post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();

3
如果你把例子中的HttpPost改成HttpPut,它也应该能够正常工作。 - Konstantin Burov
Apache客户端现在在Android上已经被弃用。 - Fakher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接