How do I send a file in Android from a mobile device to server using http?

AndroidHttpPost

Android Problem Overview


In android, how do I send a file(data) from a mobile device to server using http.

Android Solutions


Solution 1 - Android

Easy, you can use a Post request and submit your file as binary (byte array).

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
		"yourfile");
try {
	HttpClient httpclient = new DefaultHttpClient();

	HttpPost httppost = new HttpPost(url);

	InputStreamEntity reqEntity = new InputStreamEntity(
			new FileInputStream(file), -1);
	reqEntity.setContentType("binary/octet-stream");
	reqEntity.setChunked(true); // Send in multiple parts if needed
	httppost.setEntity(reqEntity);
	HttpResponse response = httpclient.execute(httppost);
	//Do something with response...

} catch (Exception e) {
	// show error
}

Solution 2 - Android

This can be done with a HTTP Post request to the server:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

Solution 3 - Android

the most effective method is to use android-async-http

You can use this code to upload a file:

// gather your request parameters
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

// send request
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
        // handle success response
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
        // handle failure response
    }
});

Note that you can put this code directly into your main Activity, no need to create a background Task explicitly. AsyncHttp will take care of that for you!

Solution 4 - Android

Wrap it all up in an Async task to avoid threading errors.

public class AsyncHttpPostTask extends AsyncTask<File, Void, String> {

	private static final String TAG = AsyncHttpPostTask.class.getSimpleName();
	private String server;

	public AsyncHttpPostTask(final String server) {
		this.server = server;
	}

	@Override
	protected String doInBackground(File... params) {
		Log.d(TAG, "doInBackground");
		HttpClient http = AndroidHttpClient.newInstance("MyApp");
		HttpPost method = new HttpPost(this.server);
		method.setEntity(new FileEntity(params[0], "text/plain"));
		try {
			HttpResponse response = http.execute(method);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			final StringBuilder out = new StringBuilder();
			String line;
			try {
				while ((line = rd.readLine()) != null) {
					out.append(line);
				}
			} catch (Exception e) {}
			// wr.close();
			try {
				rd.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// final String serverResponse = slurp(is);
			Log.d(TAG, "serverResponse: " + out.toString());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

Solution 5 - Android

the most effective method is to use org.apache.http.entity.mime.MultipartEntity;

see this code from the link using org.apache.http.entity.mime.MultipartEntity;

public class SimplePostRequestTest3 {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp");

    try {
      FileBody bin = new FileBody(new File("C:/ABC.txt"));
      StringBody comment = new StringBody("BETHECODER HttpClient Tutorials");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("fileup0", bin);
      reqEntity.addPart("fileup1", comment);
      
      reqEntity.addPart("ONE", new StringBody("11111111"));
      reqEntity.addPart("TWO", new StringBody("222222222"));
      httppost.setEntity(reqEntity);

      System.out.println("Requesting : " + httppost.getRequestLine());
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httppost, responseHandler);

      System.out.println("responseBody : " + responseBody);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }

}

##Added:

Example Link

Solution 6 - Android

For anyone still trying, you could try with retrofit2 this link.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSubratView Question on Stackoverflow
Solution 1 - AndroidEmmanuelView Answer on Stackoverflow
Solution 2 - AndroidDaGGeRRzView Answer on Stackoverflow
Solution 3 - AndroidHoshounsView Answer on Stackoverflow
Solution 4 - AndroidslottView Answer on Stackoverflow
Solution 5 - Androidjitain sharmaView Answer on Stackoverflow
Solution 6 - AndroidC-BkView Answer on Stackoverflow