使用HTTP PUT上传Android文件

Uma*_* A. 3 upload android http

我有一个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
Run Code Online (Sandbox Code Playgroud)

我写了一些代码,但它给了我错误.

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); 
Run Code Online (Sandbox Code Playgroud)

我在做什么不对劲?

Yah*_*hia 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 !}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑2 - 按照评论要求:

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