Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
1.30/5 (3 votes)
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 :
C#
[OperationContract]
[WebGet(    RequestFormat=WebMessageFormat.Json,
            ResponseFormat=WebMessageFormat.Json,
            UriTemplate = "/uploadImage?data={data}&emailID={emailID}")]

bool uploadImage(byte[] data, string emailID);


The config file endpoints:
XML
<services>
     <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>
     </service>
   </services>


Android app code :

Java
private String GetLocationInfo() {
     String loc="";
        try {
         
           bm = BitmapFactory.decodeResource(getResources(),R.drawable.testtmage);
              bos = new ByteArrayOutputStream(); 
              bm.compress(Bitmap.CompressFormat.JPEG, 40 , bos);
              
              bitmapdata=bos.toByteArray();
              
              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&emailID=acp@own.com";
           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);
            reader.read(buffer);
            stream.close();
     
            //JSONArray plates = new JSONArray(new String(buffer));
            
           
            
            for (int i = 0; i < buffer.length; i++) {
              loc+=buffer[i];
            }
            
           
             
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        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,

--Avinash
Posted

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


User defined data type:

C#
[DataContract]
    public class CustomImage
    {
        [DataMember]
        public string fileName { get; set; }
        [DataMember]
        public string[] ImageBytes { get; set; }
        [DataMember]
        public string EmailID { get; set; }
        public string DateOfBirth { get; set; }
        
    } 


Convert string[]to Image in c#:

C#
try
{
    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);
        bytes.AddRange(imageBytes);
    }

    Utils.FlowLog.getInstance().Log("Total size" + bytes.Count);

    byte[] bary = bytes.ToArray();

        byte[] imagebytes = bary;


    string fName1 =fileName;
    if (File.Exists(fName1) == true)
    {
        File.Delete(fName1);
    }

    using (FileStream sw = File.Open(fName1, FileMode.Create))
    {
        sw.Write(imagebytes, 0, imagebytes.Length);
        sw.Close();
    }
    return true;
}
catch (Exception ex)
{
    //exception logger

    return false;
}



Thanks,
Avinash
 
Share this answer
 
v2
Comments
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
You cant directly pass the bytes,convert the byte stream to BASE64 encoded string and pass it.
 
Share this answer
 
Comments
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.

--Avinash
Ashraff Ali Wahab 24-Sep-12 23:35pm    
Why it is HTTPGet when you are sending some information to the server
Hi All,
This what I did to send values to JSON WCF SERVICE from android:

Wcf service method declaration:
C#
[OperationContract]
      [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 -

Java
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 = inputStream.read(buffer)) != -1) {

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



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

Java
try
    	{
    	 
    	  InputStream is = new BufferedInputStream (getResources().openRawResource(R.drawable.gtan));
    	  
    	  JSONArray array=readBytes(is);
    	  is.close(); 	
    	     
          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", "avinash1234@gmail.com");
          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");        
          conn.setDoInput(true);
          conn.setDoOutput(true);
          conn.setRequestMethod("POST");
          conn.connect();
         
          OutputStream os =conn.getOutputStream();

          DataOutputStream out = new DataOutputStream(os);
          out.write(jo1.toString().getBytes());
          
          out.flush();
          os.close();

          int code = conn.getResponseCode();
          String message = conn.getResponseMessage();

        
          conn.disconnect();
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();    		
    	}



Thanks,
Avinash Patil
 
Share this answer
 
Comments
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

Thanks,

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900