簡體   English   中英

從Android將參數發送到.net Restful WebService

[英]Sending Parameters to .net Restful WebService from Android

我正在嘗試發送一個采用交錯數組作為參數的調用webservice方法。 我構建了數組,但始終將null傳遞給Web服務。

這是我的java類:

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();
        }
    }
}

下面是應該接收該參數的方法:我在下面的代碼中放置了一個斷點並進行了檢查。 該參數始終為空。

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;
        }

這是IStudentService中的方法聲明:

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

我按照您的建議嘗試了,但沒有成功。 它返回“請求錯誤”。這是我粘貼的示例代碼。

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

我終於讓它按我想要的方式工作。 問題是我以這種方式構建Array(請參見第1節),並將其傳遞給JSONObject或JSONArray。 我切換並使用JSONArray構建Array,並將其傳遞給JSONObject(請參閱第2節)。 它像一種魅力。

  • 第1節:這樣做的方法錯誤-(如果您要遍歷數組並將其放入JSONArray中,則可能會以這種方式工作。如果可以直接完成,這將是太多的工作。)

     String[][] Array = { new String[]{"Example", "Test"}, new String[]{"Example", "Test"}, }; JSONArray jar1 = new JSONArray(); jar1.put(0, Array); **// Did not work** 
  • 第2節:經過長時間的嘗試以及@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()); 

查看Web服務,它正是我想要的。

謝謝您的幫助!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM