Android文件上传使用HTTP PUT [英] Android File Upload Using HTTP PUT

查看:816
本文介绍了Android文件上传使用HTTP PUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有要求我的文件数据发送到HTTP URL使用PUT请求的Web服务。我知道该怎么做,但在Android中,我不知道。

I have a web service which requires me to send file data to HTTP url with PUT request. I know how to do that but in Android I don't know it.

API文档给出的示例请求。

The API docs gives a sample request.

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

我已经写了一些code,但它给了我的错误。

I have written some code but it gives me error.

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

这是一个错误,我在做什么?

Is there something wrong I am doing?

推荐答案

尝试类似的东西。

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 - 每个评论的要求:

EDIT 2 - as requested per comment:

使用 setEntity 方法,例如新FileEntity(新文件(路径),二进制/八位字节流); 作为参数调用之前执行将文件添加到PUT请求。

Use setEntity method with for example new FileEntity(new File(Path), "binary/octet-stream"); as param before calling execute to add a file to the PUT request.

这篇关于Android文件上传使用HTTP PUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆