Last Updated: September 30, 2021
· alberovalley

Upload files and data to server from android app

You want to use a http request to send data and files to a web server. Typical example of it would be editing your profile on a social network, you're sending both data and -usually- a file (your avatar).

Following snippet should be within an AsyncTask or similar, it must not be within the UI thread, for latest Android versions will simply kill your app if you do http requests on the main UI thread.

It needs the following imports:

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

And here's the code

HttpClient httpClient = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
try {
     HttpPost request = new HttpPost(TapabookUrls.urlSubirTapa);

     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
     entity.addPart("String_Data_Parameter_Name", new StringBody("String_Value"));
     entity.addPart("Numeric_Data_Parameter_Name", new StringBody( NumericValue +""));


     File f = new File(Environment.getExternalStorageDirectory()
                 + File.separator + "test.jpg");
     //write the bytes in file
     FileOutputStream fo = new FileOutputStream(f);
     // remember close the FileOutput
     FileBody picBody = new FileBody(f, "image/jpeg");


 entity.addPart("File_Parameter_Name", picBody);
 HttpResponse response = httpClient.execute(request);
 StatusLine statusLine = response.getStatusLine();
 int statusCode = statusLine.getStatusCode();
 if (statusCode == 200) {
                     HttpEntity responseEntity = response.getEntity();
     InputStream content = responseEntity.getContent();      
                 BufferedReader reader = new BufferedReader(new InputStreamReader(content));

             String line;
             while ((line = reader.readLine()) != null) {
             json = builder.toString();
             Tapabook.d( "SubeTapaAsincrono json : " + json);

     } catch (IllegalStateException e) {
         Log.e( "FileUpload IllegalStateException ", e.getMessage() );
     } catch (IOException e) {
         Log.e( "FileUpload IOException ", e.getMessage() );
             } catch (ParseException e) {
         Log.e( "FileUpload ParseException " + e.getMessage() );

     } finally {
         // close connections