我有一个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请求.