In this post I will be writing about how to upload media on to word-press site using the Media api from wp-api library.

Again the reason for writing this is same, not enough info on this particular topic, and few people are stuck in the same issue I faced.

Another reason for writing is that, if you intend to code this up on to Java, it will work, but the Android HTTP classes are a bit different and the headers they were sending was slightly different than the same classes on Java.

Lets start.

For simplicity we will use a third party HTTP library, HttpRequest by Kevin.

In order to get the api work, at minimum we require 2 fields, 1st is the file and other the title.
Thus we get the following code:


HttpRequest request = HttpRequest.post(url);
request.authorization("Basic "+ah);
request.part("file", fName+".png", "image/png", new File(file));
request.part("title", "test");
if(request.code()==201) {
StringWriter sw = new StringWriter();
request.receive(sw);
onMedia(Media.parse(new JsonParser().parse(sw.toString()).getAsJsonObject()));
}else
onError(new Exception("Unable to upload."));
StringWriter sw = new StringWriter();
request.receive(sw);
Log.i(request.code()+" - "+request.toString());

I hope this will help a lot to those that have been struggling on to this.

Have a nice day.

Leave a Reply