0

I am trying to send an invoke a webservice method that took a jagged array as a parameters. I build the array, but it always passed null to the web service.

Here is my java class:

package com.mitch.wcfwebserviceexample;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity implements OnClickListener {
    private String values ="";
  Button btn;
  TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button)this.findViewById(R.id.btnAccess);
        tv = (TextView)this.findViewById(R.id.tvAccess);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) {
        try
        {
        AsyncTaskExample task = new AsyncTaskExample(this);
        task.execute("");
        String  test = values;
        tv.setText(values);
        } catch(Exception e)
        {
           Log.e("Click Exception ", e.getMessage());   
        }

    }

    public class AsyncTaskExample extends AsyncTask<String, Void,String>
    {
        private String Result="";
        //private final static String SERVICE_URI = "http://10.0.2.2:1736";
        private final static String SERVICE_URI = "http://10.0.2.2:65031/SampleService.svc";
        private MainActivity host;
        public AsyncTaskExample(MainActivity host)
        {
            this.host = host;
        }

        public String GetSEssion(String URL)
        {
          boolean isValid = true;
          if(isValid)
          {

                    String[][] val = {
                        new String[] {"Student.ID","123456"},
                        new String[] {"Student.username","user1"},
                        new String[] {"Student.password","123456"},
                        new String[] {"Student.location.id","12"}
                    };
                    HttpPost requestAuth = new HttpPost(URL +"/Login");
                    try
                  {
                    JSONObject json = new JSONObject();
                //  json.put("sessionId", sessionId);
                    JSONArray params = new JSONArray();
                    params.put(val);
                    json.put("authenParams", params);

                    StringEntity se = new StringEntity(json.toString());
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    requestAuth.setHeader("Accept","application/json");
                    requestAuth.setEntity(se);
                    DefaultHttpClient httpClientAuth = new DefaultHttpClient();
                    HttpResponse responseAuth = httpClientAuth.execute(requestAuth);
                    HttpEntity responseEntityAuth = responseAuth.getEntity();
                    char[] bufferAuth = new char[(int)responseEntityAuth.getContentLength()];
                    InputStream streamAuth = responseEntityAuth.getContent();
                    InputStreamReader readerAuth = new InputStreamReader(streamAuth);
                    readerAuth.read(bufferAuth);
                    streamAuth.close();
                    String rawAuthResult = new String(bufferAuth);
                    Result = rawAuthResult;
                    String d = null;
        //      }
            } catch (ClientProtocolException e) {
                Log.e("Client Protocol", e.getMessage());
            } catch (IOException e) {
                Log.e("Client Protocol", e.getMessage() );
            } catch(Exception e)
            {
                Log.e("Client Protocol", e.getMessage() );
            }
          }
          return Result;
        }

        @Override
        protected String doInBackground(String... arg0) {
            android.os.Debug.waitForDebugger();
            String t = GetSEssion(SERVICE_URI);
            return t;
        }

        @Override
        protected void onPostExecute(String result) {
        //  host.values = Result;
            super.onPostExecute(result);
        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
        }
    }
}

Below is my method that is supposed to recieve the parameter: I put a break point in the code below and check it. The parameter is always null.

public string Login(string[][] value)
        {
            string[] tester = null;
            string testerExample="";
            foreach (string[] st in value)
            {
                tester = st;
            }

            foreach (string dt in tester)
            {
                testerExample = dt;
            }

            return testerExample;
        }

Here is the method declaration in IStudentService:

[OperationContract]
        [WebInvoke(
            Method="POST", UriTemplate="Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string Login(string[][] value);

I tried to as you suggested, and it did not work. It return "Request Error" Here is the sample code that I paste.

HttpClient client = new DefaultHttpClient();  
           HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/login");   
 List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
pairs.add(new BasicNameValuePair("tester","abcd"));  
pairs.add(new BasicNameValuePair("sampletest","1234"));  
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);  
post.setEntity(entity);  
HttpResponse response = client.execute(post); 
HttpEntity responseEntity = response.getEntity();               
char[] buffer = new char[(int)responseEntity.getContentLength()];        
InputStream stream = responseEntity.getContent();        
InputStreamReader reader = new InputStreamReader(stream);        
reader.read(buffer);        stream.close();         
String value = new String(buffer);
Josiane Ferice
  • 921
  • 5
  • 15
  • 31
  • Why do you use `StringEntity`? Use `UrlEncodedFormEntity`, it is better. – vortexwolf May 08 '13 at 15:24
  • I did as you suggested, and it did not work for me. It returns request Error. – Josiane Ferice May 08 '13 at 18:47
  • Try to compose a http request by using the Fiddler application. Though I don't think that it is possible to call a service that takes `string[][] value` as an argument. You should replace it by something like `string Login(string tester, string sampletest)`. – vortexwolf May 08 '13 at 20:05
  • I tried your suggestion string Login(string tester, string sampletest), and it worked fine. I see the expected coming over to the webservice. – Josiane Ferice May 09 '13 at 00:39
  • I tried using a single dimensional array with no luck either. The log simply says Request Error. It did not reached the method because I have a try catch that would return a message if an exception occurs. – Josiane Ferice May 09 '13 at 01:29
  • why do you use an array instead of normal parameters? Even if so, you should try to reproduce the request by using Fiddler. The post entity should be like `values[0]=111&values[1]=222`. – vortexwolf May 09 '13 at 09:20
  • The person who created the webservice is a c++ guy, so he used jagged array instead of normal array. I've requested that they change it normal parameters, but the request was not approved. As far as Fiddler, I can't install it on my machine because IT will not approved. – Josiane Ferice May 09 '13 at 13:58
  • 1
    @vorrtex you are wrong!! for sending JSON you should not use `UrlEncodedFormEntity` – Selvin May 09 '13 at 15:06
  • Then I would create a test console application and try to send random different strings until one of them is accepted. That's the only solution if your company prevents you from doing your work. Though I can try to implement a test sample and try to compose a request myself. @Selvin yes, for sending json, but normal web services work in a different way, they accept application/x-www-form-urlencoded and multipart/form-data. – vortexwolf May 09 '13 at 16:50
  • It is exactly what I've been doing, and it's taking a really long time. After your post yesterday, I was able to get the normal string to work using StringEntity. Then, I try to get to it to work using Array; it refused to work. After a while, I started using UrlEncodedFormEntity to see if I could pass in a simpled string parameter. I am still fighting with it, and won't give up until I get one of them to work, lol. Thank for your help! – Josiane Ferice May 09 '13 at 16:58

1 Answers1

0

I finally got it to work they way that I want it to. The issue was that I was building the Array this way (see below section 1) and pass it to the JSONObject or JSONArray. I switched and build the Array using JSONArray and pass it to the JSONObject (see section 2). It works like a charm.

  • Section1: Wrong way to do it - (It may work this way if you were to look through the array and put them in a JSONArray. It's will be too much work when it can be done directly.)

    String[][] Array = {
    new String[]{"Example", "Test"},
    new String[]{"Example", "Test"},
    };
    
    JSONArray jar1 = new JSONArray();
    jar1.put(0, Array); **// Did not work**
    
  • Section 2: The way I did it after long hours of trying and some very helpful tips and hints from @vorrtex.

    JSONArray jar1 = new JSONArray();
    jar1.put(0, "ABC");
    jar1.put(1, "Son");
    jar1.put(2, "Niece");
    
    JSONArray jarr = new JSONArray();
    jarr.put(0, jar1);
    
    JSONArray j = new JSONArray();
    j.put(0,"session");
    
    JSONObject obj = new JSONObject();          
    obj.put("value", jarr);
    obj.put("test", j);
    obj.put("name","myName");
    Log.d("Obj.ToString message: ",obj.toString());
    StringEntity entity = new StringEntity(obj.toString());
    

Looking at the web service, and it has exactly what I was looking for.

Thanks for you help!!!!

GAMA
  • 5,958
  • 14
  • 79
  • 126
Josiane Ferice
  • 921
  • 5
  • 15
  • 31