2011-08-23 71 views
3

我有一个Web服务,它需要我发送文件数据到HTTP URL与PUT请求。我知道如何做,但在Android我不知道。Android文件上传使用HTTP PUT

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); 

我在做什么错?

回答

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

EDIT 2 - 的要求每条评论:

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

+0

我们怎样才能把这些图像字节的数据到PUT?我需要把它放到实体上,然后放到PUT上吗? – Neutralizer

+0

看到我的编辑2 - 基本上是的,你必须使用'setEntity' ... – Yahia

+0

它的工作! (一个该死的限制) – Neutralizer

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(); 
+1

当服务器不期望PUT时它工作正常 - 请参阅OP要求.. – Yahia

+0

但不幸的是PUT – Neutralizer

+3

如果您要将示例中的HttpPost更改为HttpPut,它也应该可以正常工作。 –