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

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

问题描述

我有一个网络服务,它要求我通过 PUT 请求将文件数据发送到 HTTP url.我知道怎么做,但在 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

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

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

我做错了什么吗?

推荐答案

尝试类似

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<推荐使用/code> - 示例参见 http://massapi.com/class/org/apache/http/client/methods/HttpPut.java.html

Using the built-in HttpPut is recommended - examples see http://massapi.com/class/org/apache/http/client/methods/HttpPut.java.html

编辑 2 - 根据评论的要求:

EDIT 2 - as requested per comment:

在调用 execute<之前使用 setEntity 方法,例如 new FileEntity(new File(Path), "binary/octet-stream"); 作为参数/code> 将文件添加到 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.

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

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