Skip to content
Advertisement

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("http://10.0.2.2:1374/uploaditem");
    JSONStringer json = JSONStringer()
        .object()
        .key("ipm")
            .object()
                .key("name").value("test")
                .key("description").value("asfa")
                .key("categoryid").value(1)
                .key("data").value(ConvertImgToBase64Str(img))
                .key("imagetype").value(2)
                .key("tags").value("test;test")
            .endObject()
         .endObject();

    StringEntity entity = new StringEntity(json.toString());
    entity.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8                  
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
    httpost.setEntity(entity); 
    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?

Answer

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.

EDIT

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.

Advertisement