开发者

Android File Upload Using HTTP PUT

开发者 https://www.devze.com 2023-03-29 22:22 出处:网络
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.

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.

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

Is there something wrong I am doing?


try something similar to

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 !}

EDIT - another and better option:

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

EDIT 2 - as requested per comment:

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.


The following code works fine for me:

URI uri = new URI(url);
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);

File file = new File(filename);         

MultipartEntity entity = new MultipartEntity();
ContentBody body = new FileBody(file, "image/jpeg");
entity.addPart("userfile", body);

post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();
0

精彩评论

暂无评论...
验证码 换一张
取 消