Skip to content

Posting image to wcf rest service from Android

I’m having a problem to post a image to my wcf rest service. I’m posting some parameters of which one of them is a base64 utf-8 encoded string (the image).

My problem is that every time I post I get “bad request”. Here is the code

public String PostImage(Drawable img) throws Exception 
    HttpPost httpost = new HttpPost("");
    JSONStringer json = JSONStringer()

    StringEntity entity = new StringEntity(json.toString());
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
    return ExcecutePostRequest(httpclient,httpost);

//Method to convert the image to base64encoded string
private String ConvertImgToBase64Str(Drawable img) {
    Bitmap bitmap = ((BitmapDrawable)img).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bitmapdata = stream.toByteArray();
    return Base64.encodeToString(bitmapdata, Base64.URL_SAFE);

It is something with the encoded string, but what?


I don’t see why it should be a problem with the encoded string.

Firstly, try removing the data attribute in the string object and see if you get the same problem. This way you can eliminate the possibility it is due to the the encoding and ensure you are making the request correctly.

Secondly print the http message being sent and format check it. If you have access to the server log the message being received and any details that may elaborate on the Bad Request. I would have thought WCF will be printing something to stderr if it is responding with a bad request so try just checking the existing logs first.


I don’t think there should be problems with strange characters because the character used in base64 encoding don’t fall outside the ASCi range.

You should check the size of the request being sent. If you images are big you will get a big base64 encoded string which might exceed the server post limit.

If you can’t get to the server logs which I think would clarify this if it was the problem you could test it by sending a smaller image.