Click here to Skip to main content
12,395,871 members (61,699 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: Java Mobile WCF Android JSON , +
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 :
[OperationContract]
[WebGet(    RequestFormat=WebMessageFormat.Json,
            ResponseFormat=WebMessageFormat.Json,
            UriTemplate = "/uploadImage?data={data}&emailID={emailID}")]
 
bool uploadImage(byte[] data, string emailID);

The config file endpoints:
<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 :

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 24-Sep-12 1:00am
Rate this: bad
 
good
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:

[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#:

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
  Permalink  
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
Rate this: bad
 
good
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.
  Permalink  
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
Rate this: bad
 
good
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:
[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 -

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 :

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
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160721.1 | Last Updated 4 Oct 2012
Copyright © CodeProject, 1999-2016
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