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 Answers1

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)

Community
  • 1
  • 1
sschrass
  • 6,331
  • 6
  • 39
  • 53