Click here to Skip to main content
12,948,385 members (65,114 online)
Rate this:
Please Sign up or sign in to vote.
Hi All,

I am trying to pass byte[] to JSON Service from the Android App but I am getting an error message "not allowed".
Service Method I am using :
[WebGet(    RequestFormat=WebMessageFormat.Json,
            UriTemplate = "/uploadImage?data={data}&emailID={emailID}")]
bool uploadImage(byte[] data, string emailID);

The config file endpoints:
     <service behaviorConfiguration="WebServiceBehaviour" name="WcfService.Service1">
       <endpoint address="" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="WcfService.IService1"></endpoint>
       <endpoint address="soap" binding="basicHttpBinding" contract="WcfService.IService1"></endpoint>

Android app code :

private String GetLocationInfo() {
     String loc="";
        try {
           bm = BitmapFactory.decodeResource(getResources(),R.drawable.testtmage);
              bos = new ByteArrayOutputStream(); 
              bm.compress(Bitmap.CompressFormat.JPEG, 40 , bos);
              String imgData=Base64.encodeToString(bitmapdata,Base64.DEFAULT);
           String img=imgData.replace("\n", "%20");
            // Send GET request to <service>/GetPlates
           String url=SERVICE_URI + "/uploadImage?data=bitmapdata&";
           HttpGet request = new HttpGet();
           request.setURI(new URI(url));
           request.setHeader("Accept", "application/json");
           request.setHeader("Content-type", "application/json");
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);
            HttpEntity responseEntity = response.getEntity();
            // Read response data into buffer
            char[] buffer = new char[(int)responseEntity.getContentLength()];
            InputStream stream = responseEntity.getContent();
            InputStreamReader reader = new InputStreamReader(stream);
            //JSONArray plates = new JSONArray(new String(buffer));
            for (int i = 0; i < buffer.length; i++) {
        } catch (Exception e) {
        return loc;

If there is any other solution to pass image bytes from android to JSON Wcf service please suggest.
I am not much familiar with java coding, your help is much appreciated.

Thanks in advance,

Posted 24-Sep-12 1:00am
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Hi ,
Here is the service implementation:
<pre lang="cs">[OperationContract]
       [WebInvoke(Method="POST", RequestFormat = WebMessageFormat.Xml,
           ResponseFormat = WebMessageFormat.Xml,
           UriTemplate = "/TestMethod")]
       bool TestMethod(CustomImage cust);

User defined data type:

    public class CustomImage
        public string fileName { get; set; }
        public string[] ImageBytes { get; set; }
        public string EmailID { get; set; }
        public string DateOfBirth { get; set; }

Convert string[]to Image in c#:

                byte[] total_size = new byte[data.Length];
                List<byte> bytes = new System.Collections.Generic.List<byte>();
                foreach (string str in data)
                    //combine image bytes
                    byte[] imageBytes = Convert.FromBase64String(str);
                Utils.FlowLog.getInstance().Log("Total size" + bytes.Count);
                byte[] bary = bytes.ToArray();
                    byte[] imagebytes = bary;
                string fName1 =fileName;
                if (File.Exists(fName1) == true)
                using (FileStream sw = File.Open(fName1, FileMode.Create))
                    sw.Write(imagebytes, 0, imagebytes.Length);
                return true;
            catch (Exception ex)
                //exception logger
                return false;

veerasamrat 30-Dec-13 6:10am
@Avinash can you please provide complete TestMethod(CustomImage cust) method?
veerasamrat 6-Aug-14 9:05am
@Avinash, thank you very much for your code
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You cant directly pass the bytes,convert the byte stream to BASE64 encoded string and pass it.
Avinash6474 24-Sep-12 21:57pm
Hi Ashraff Ali,
Thank you for your suggession.
I tried by converting the byte array to Base64 string and I passed the converted string as a parameter but it showing an error "URL length excised the max limit".
How to overcome on this issue.

Ashraff Ali Wahab 24-Sep-12 23:35pm
Why it is HTTPGet when you are sending some information to the server
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Hi All,
This what I did to send values to JSON WCF SERVICE from android:

Wcf service method declaration:
      [WebInvoke(Method="POST", RequestFormat = WebMessageFormat.Xml,
          ResponseFormat = WebMessageFormat.Xml,
          UriTemplate = "/TestMethod")]
      bool TestMethod(CustomImage cust);

This function is giving the array of bytes of image to be uploading -

public JSONArray readBytes(InputStream inputStream) throws IOException, JSONException {

         int bufferSize = 1024;
         byte[] buffer = new byte[bufferSize];
         JSONArray array=new JSONArray();
         int len = 0,i=0;
         while ((len = != -1) {

           ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
           byteBuffer.write(buffer, 0, len);
           byte[] b= byteBuffer.toByteArray();
           array.put(i,Base64.encodeToString(b, Base64.DEFAULT));
         return array;

Following is the way to pass class object to JSON WCF Service :

    	  InputStream is = new BufferedInputStream (getResources().openRawResource(R.drawable.gtan));
    	  JSONArray array=readBytes(is);
          URI uri = new URI(SERVICE_URI+ "/TestMethod");
          JSONObject jo1 = new JSONObject();
          jo1.put("fileName", "avi.jpg");
          jo1.put("ImageBytes",array); // assign value to string[]
          jo1.put("EmailID", "");
          jo1.put("SkinCareInterest", "Acne");
          jo1.put("LightSource", "Sunny");
          jo1.put("SkinType", "3");
          jo1.put("DateOfBirth", "1987-09-15");
          jo1.put("UserName", "BTBP");
          jo1.put("Password", "BTBP");
          HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
          conn.setConnectTimeout(5*1000*3600); //set time out    
          conn.setReadTimeout(5*1000*3600);   // set socket time out
          conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
          conn.setRequestProperty("Accept", "application/json");          
          conn.setRequestProperty("Connection", "Keep-Alive"); 
          conn.setRequestProperty("User-Agent", "Pigeon");        
          OutputStream os =conn.getOutputStream();
          DataOutputStream out = new DataOutputStream(os);
          int code = conn.getResponseCode();
          String message = conn.getResponseMessage();
    	catch(Exception ex)

Avinash Patil
nakash2050 2-Oct-12 10:48am
Hi Avinash,

Could you please upload the implementation of your WCF method bool TestMethod(CustomImage cust); along with the DataContract implementation of "CustomImage". My requirement is similar to yours. But need to send a "Stream" object as JSON


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 5,344
CHill60 3,275
Maciej Los 2,703
Jochen Arndt 1,935
ppolymorphe 1,795

Advertise | Privacy | Mobile
Web02 | 2.8.170524.1 | Last Updated 4 Oct 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100