2011-08-23 73 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,它也應該可以正常工作。 –