Android File Upload Using HTTP PUT
15,750
Solution 1
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.
Solution 2
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();
Author by
Umair A.
Updated on June 25, 2022Comments
-
Umair A. almost 2 years
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?
-
Umair A. over 12 yearsHow can we put those image bytes data to the PUT? do I need to put that to entity and then entity to the PUT?
-
Konstantin Burov over 12 yearsIf you'd change HttpPost in the example to HttpPut it should work as well.
-
osayilgan over 9 years@Yahia your first edit is the best solution I've found so far.
-
KarnakerReddy Gaddampally over 8 yearshow to add the header to the put method?
-
Fakher over 7 yearsthe apache client is deprecated now on Android