微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用HTTP PUT上传Android文件

我有一个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); 

我在做什么不对劲?

解决方法:

尝试类似的东西

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方法,例如new FileEntity(new File(Path),“binary / octet-stream”);在调用execute之前将param作为param添加文件到PUT请求.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐