Search code examples
javaandroidhttpurlconnectionandroid-6.0-marshmallowapache-commons-httpclient

org.apache.http.entity.FileEntity is deprecated in Android 6 (Marshmallow)


I'm upgrading an app to API 23 where org.apache.http is deprecated.

My current (deprecated) code looks like this:

HttpClient httpClient = new DefaultHttpClient();
File file = new File(attr.Value);
String url = server_url;
HttpPost request = new HttpPost(url);
FileEntity fileEntity = new FileEntity(file, "image/png");
request.setEntity(fileEntity);
HttpResponse response = httpClient.execute(request);
String output = getContent(response.getEntity().getContent());

I've found some suggestions to how this should be done using HttpURLConnection, but they are all much more complex then the current solution (which cannot be used anymore). I'm talking about many lines of code for executing the same functionality as the above.

Examples are: this page and this page

Does anyone have a good solid shorter solution for that?


Solution

  • If you change your compileSdkVersion to 21, your app will compile cleanly. That being said, there are reasons why Google is backing away from the built-in HttpClient implementation, so you probably should pursue some other library. That "some other library" could be:

    • the built-in classic Java HttpUrlConnection, though as you have found, its API leaves something to be desired
    • Apache's independent packaging of HttpClient for Android
    • OkHttp (my recommendation)
    • AndroidAsync

    In particular, OkHttp seems to have a pretty good API for posting a file and posting a multipart form, which should be similar to what your HttpClient code is doing.