使用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请求.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...