2013-05-08 73 views
0

我想发送一个webservice方法,将锯齿状数组作为参数。我构建数组,但它总是将null传递给Web服务。将参数发送到.net从Android的Restful WebService

这里是我的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); 
+0

为什么你使用'StringEntity'?使用'UrlEncodedFormEntity',它更好。 – vorrtex 2013-05-08 15:24:47

+0

我按照你的建议做了,它对我没有用。它返回请求错误。 – 2013-05-08 18:47:35

+0

尝试使用Fiddler应用程序撰写http请求。虽然我不认为有可能调用一个将'string [] [] value'作为参数的服务。你应该用'string Login(string tester,string sampletest)'来代替它。 – vorrtex 2013-05-08 20:05:50

回答

0

我改变了网络服务合同,XML,以及UrlEncodedFormEntity仍然无法正常工作。

public interface SampleService 
    { 
     [OperationContract] 
     [WebInvoke(
      Method="POST", UriTemplate="/Login", ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)] 
     string Login(List<String> value); 
    } 
+0

尝试再次使用StringEntity,并完全像这样创建它'new StringEntity(“[\”str1 \“,\”str2 \“]”)''。然后检查它是否被接受。 – vorrtex 2013-05-09 16:55:26

+0

OMG ....它的工作原理......它的工作原理......它的工作原理......这是否意味着我构建字符串的方式导致了这个问题? – 2013-05-09 17:09:36

+0

是的,也许正因为如此,'JSONObject'类没有像它应该那样工作。所以你应该检查一下'json.toString()'返回的是否在逻辑上是正确的。二维数组应该看起来像'[[\“str1 \”,...其他值...]]。如果您使用1维数组,它应该包含您已经看到的单个括号。 – vorrtex 2013-05-09 17:16:46

0

我终于按照他们希望的方式工作了。问题在于我以这种方式构建数组(请参见下面的第1节)并将其传递给JSONObject或JSONArray。我使用JSONArray切换并构建数组,并将其传递给JSONObject(请参阅第2节)。它像一个魅力。

  • SECTION1: 错误的方式做到这一点 - (它可能以这种方式工作,如果你是通过数组来看看,并把它们放在一个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服务,它具有正是我一直在寻找。

谢谢你的帮助!

+0

好的,请将您自己的答案标记为已接受。 – vorrtex 2013-05-09 21:33:04

相关问题