2

In Android, it seems so confusing how to upload a binary file to a server because some libraries have become outdated and there's a lack of information which approach should be used nowadays. Could anyone give a pointer of how to upload a binary or whatever file to a server in Android?

I'd prefer not to use any dependencies, unless they really are neccessary.

1
  • Try retrofit it is really helpful for any kind of server interaction! Commented Jan 8, 2016 at 15:04

1 Answer 1

0

In lack of information what kind of server this might be, I've found this

OkHttpClient client = new OkHttpClient(); OutputStream out = null; try { URL url = new URL("http://www.example.com"); HttpURLConnection connection = client.open(url); for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } connection.setRequestMethod("POST"); // Write the request. out = connection.getOutputStream(); multipart.writeBodyTo(out); out.close(); // Read the response. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected HTTP response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { try { if (out != null) out.close(); } catch (Exception e) {} } 

I assume that the deprecated/outdated library you mentioned would be ApacheHttpClient, therefore I recommend OkHttp (that is using HttpUrlConnectionI believe) instead.

To add OkHttp as dependency you can edit your build.gradle like:

dependencies { //some other dependencies compile 'com.squareup.okhttp:okhttp:2.7.2' } 

Available versions can be found here: mvnrepository (no need to download them manually, just add them like above, gradle will download them itself)

Sign up to request clarification or add additional context in comments.

2 Comments

what dependencies should I use and how to add them?
hey, it seems "client" has no method called "open()".