2013-05-09 100 views
1

我不確定導致請求不執行的原因。我試圖在android中調用WCF Restful服務,並收到錯誤消息「Request Error」。看看這個例子,我沒有看到這個例子不適用的原因。請看下圖:在Android中使用Restful WCF服務

這裏是.NET服務:

[ServiceContract] 
    public interface ISampleService 
    { 
     [OperationContract] 
     [WebInvoke(
      Method="POST", UriTemplate="/Login", BodyStyle= WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
     string Login(string value); 
    } 

public class SampleService : ISampleService 
    { 
     public string Login(string value) 
     { 
      string t = ""; 
      try 
      { 
       //foreach (string s in value) 
       //{ 
       // t = s; 
       //} 
       return t; 
      } 
      catch (Exception e) 
      { 
       return e.ToString(); 
      } 
     } 
    } 

的Java:

package com.mitch.wcfwebserviceexample; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.ByteArrayEntity; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicHeader; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.protocol.HTTP; 
import org.json.JSONArray; 
import org.json.JSONObject; 
import org.json.JSONStringer; 

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:8889"; 
     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) 
      { 

       HttpClient client = new DefaultHttpClient(); 
       HttpPost post = new HttpPost("http://10.0.2.2:65031/SampleService.svc/Login"); 
       try 
       { 
       List<NameValuePair> value = new ArrayList<NameValuePair>(1); 
       value.add(new BasicNameValuePair("value", "123456")); 
       post.setEntity(new UrlEncodedFormEntity(value)); 
       HttpResponse response = client.execute(post) ; 
       BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
       String line =""; 
       while((line = rd.readLine()) != null) 
       { 
        System.out.println(line); 
       } 
       }catch(Exception e) 
       { 
        Log.e("Error", 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(); 
     } 
    } 
} 
+0

url ecoded form不是JSON ...服務期望得到JSON ...使用'new StringEntity(「{」value \「:\」123456 \「}」)'而不是'UrlEncodedFormEntity' .. 。因爲你的代碼發送'value = 123456',你需要發送'{「value」:「123456」}' – Selvin 2013-05-09 15:02:36

+0

我認爲最好使用URLEncodedFormatEntity而不是StringEntity。我使用的是StringEntity,它對於簡單的參數工作正常。但是,當wcf方法期待數組或Jagged數組時,我正在收到「Request Error」消息。例如,服務契約以這種方式描述string [] [] Login(string [] [] value)。我對此感到非常難過。 – 2013-05-09 15:15:21

回答

1

我終於得到了它的工作方式,他們說我希望它。問題在於我以這種方式構建數組(請參見下面的第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); 

//沒有工作 第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

我有問題,我有我的arraylist多個數據,然後我怎麼能解析它在傑森。我有id,姓名,地址,電話號碼arraylist,我想通過這個webservice中的所有數據 – PankajAndroid 2013-11-18 13:58:48

+0

我正在使用一個二維數組。但是,您應該能夠遍歷列表並創建將發送到Web服務的JSONObject。 – 2013-11-18 15:19:41