It’s been a little while since I’ve done any really serious Android development, but a couple of projects have brought me back to it.
Early on in one of those projects I had to make some HTTP requests, my first thought was to make use of the Apache HTTP Client classes as I had done many times before on Android. Which is why I was a little surprised when the usual ctrl-space didn’t auto complete any of the expected class names.
It turns out the classes were removed in Android 6.0 and the notice suggests using the HttpURLConnection class. A little bit more digging turned up a wrapper for this called Volley.
Volley is a wrapper round the HttpURLConnection class to provides a neat asynchronous interface that does IO in the background and then delivers results to the Main thread so UI updates can be done with out further faffing around switching threads. There is also a nice set of tutorials on the Android Developers pages.
The first few requests all worked fine, but there was one which was a little bit more tricky. The HTTP endpoint in question accepts a multipart-form payload. A bit of googling/searching on Stackoverflow turned up a number of approaches to this and best seamed to be documented in this gist
This was close to what I wanted but not quite what I needed so I have taken some of the core concepts and built my own MultipathRequest object.
... MultipartRequest request = new MultipartRequest(url, headers, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { ... } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { ... } }); request.addPart(new FormPart(fieldName,value)); request.addPart(new FilePart(fileFieldName, mimeType, fileName, data); requestQueue.add(request); ...
I’ve stuck the code up on github here. You can include it in your Android Project by adding the following to the build.gradle in the root of the project:
allprojects { repositories { ... maven { url 'https://jitpack.io' } } }
And then this to the dependencies section of the modules build.gradle:
dependencies { compile 'com.github.hardillb:MultiPartVolley:0.0.3' }