使用HTTP PUT上传Android文件

时间:2011-08-23 15:12:23

标签: android http upload

我有一个Web服务,要求我使用PUT请求将文件数据发送到HTTP URL。我知道怎么做但在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); 

我有什么问题吗?

2 个答案:

答案 0 :(得分: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 - 根据评论的要求:

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

答案 1 :(得分: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();