Android客戶端調用Asp.net的WebService – Android移動開發技術文章_手機開發 Android移動開發教學課程

 

在Android端為瞭與服務器端進行通信有幾種方法:1、Socket通信2、WCF通信3、WebService通信。因為ASP.net中發佈WebService非常簡單,所以我們選擇用WebService來進行通信。在Android端調用.Net的WebService又有兩種方法:1、開源的ksoap-2類庫進行soap通信2、通過Http請求來調用,我們選擇第二種方法,簡單快捷。

首先,先準備服務器端,在web.config裡面的的system.Web節點添加

 

 

<webServices> 

       <protocols> 

         <add name= "HttpPost"/> 

         <add name= "HttpGet"/> 

       </protocols> 

     </webServices> 

 

否則通過“WsUrl/方法”的路徑訪問WebService時會出現“因URL 意外地以“/方法名”結束,請求格式無法識別。執行當前Web 請求期間生成瞭未處理的異常。可以使用下面的異常堆棧跟蹤信息確定有關異常原因和發生位置的信息。 ”的錯誤。在IIS中部署網站,分配“8082”端口給該網站,然後在Windows防火墻的“高級設置”中添加“入站規則”,將“8082”端口添加訪問權限到入站規則中,如果不添加入站規則,則在打開windows防火墻的情況下局域網內的客戶端是不能夠通過"https://192.168.1.122:8082"訪問到該網站的,會顯示“無法打開網頁”的錯誤,因此更不可能通過“https://192.168.1.122:8082/WebServices/TestService.asmx/GetUserList”訪問到WebMethod。新建一個名為TestService.asmx的WebService,並在TestService.asmx中新建兩個方法,一個帶參數,一個不帶參數,如下:

 

 

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Web; 

using System.Web.Services; 

//using System.Web.Script.Services;//[ScriptMethod(ResponseFormat=ResponseFormat.Json)]所需引用的命名空間 

using BLL; 

using Model; 

namespace Test.WebServices 

    /// <summary> 

    /// TestService的摘要說明 

    /// </summary> 

    [WebService(Namespace = "https://www.testservice.com/")] 

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 

    [System.ComponentModel.ToolboxItem(false)] 

    // 若要允許使用ASP.NET AJAX 從腳本中調用此Web 服務,請取消對下行的註釋。 

     [System.Web.Script.Services.ScriptService]//這個屬性必須把註釋取消掉 

    public class TestService: System.Web.Services.WebService 

    { 

 

        [WebMethod]       

        //[ScriptMethod(ResponseFormat=ResponseFormat.Json)] 

        public string HelloWorld() 

        { 

            return "Hello World"; 

        } 

        [WebMethod] 

       // [ScriptMethod(ResponseFormat = ResponseFormat.Json)]//不需要該屬性,Android端設置Http頭的Content-Type為application/json即可返回JSON數據格式給客戶端 

        public List<ModelUser> GetUserList() 

        { 

            BLLUser bllUser = new BLLUser(); 

            return bllUser.GetModelList(); 

        } 

        [WebMethod] 

        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

        public ModelUser GetUserByUserName(string strUserName) 

        { 

            BLLUser bllUser = new BLLUser(); 

            return bllUser.GetModel(strUserName); 

        } 

    } 

    public class ModelUser 

    { 

    public string UserName{get;set;}; 

    public string Password{get;set;}; 

    } 

www.aiwalls.com

ASP.net服務器端的的代碼準備好之後開始編寫Android客戶端的代碼,如下:

 

package com.wac.Android.TestService; 

 

import java.io.BufferedReader; 

import java.io.IOException; 

import java.io.InputStream; 

import java.io.InputStreamReader; 

 

import org.apache.http.HttpEntity; 

import org.apache.http.HttpHost; 

import org.apache.http.HttpResponse; 

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.StringEntity; 

import org.apache.http.impl.client.DefaultHttpClient; 

import org.apache.http.protocol.HTTP; 

import org.apache.http.util.EntityUtils; 

import org.json.JSONArray; 

import org.json.JSONException; 

import org.json.JSONObject; 

 

import android.app.Activity; 

import android.os.Bundle; 

import android.util.Log; 

import android.view.View; 

import android.view.View.OnClickListener; 

import android.widget.TextView; 

import android.widget.Button; 

 

public class TestServiceActivity extends Activity { 

    private static final String TAG = "TestService"; 

 

    /** Called when the activity is first created. */ 

    @Override 

    public void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState);    

        setContentView(R.layout.main); 

 

        OnClickListener listener = new OnClickListener() { 

            public void onClick(View v) {                

                 try {   

             //1、調用不帶參數的WebMethod 

                     final String SERVER_URL = "https://192.168.1.122:8082/WebServices/TestService.asmx/GetUserList";           

                     HttpPost request = new HttpPost(SERVER_URL); // 根據內容來源地址創建一個Http請求   

                     request.addHeader("Content-Type", "application/json; charset=utf-8");//必須要添加該Http頭才能調用WebMethod時返回JSON數據             

                     HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 發送請求並獲取反饋                     

                     // 解析返回的內容                       

                     if (httpResponse.getStatusLine().getStatusCode() !=404)  //StatusCode為200表示與服務端連接成功,404為連接不成功 

 

                     {   

                 //因為GetUserList返回的是List<ModelUser>,所以該數據的JSON格式為: 

                 //{"d":[{"__type":"Model.ModelUser","UserName":"wa1","Password":"123"},{"__type":"Model.ModelUser","UserName":"wa2","Password":"123"}]} 

                             String result = EntityUtils.toString(httpResponse.getEntity());  

                 Log.i("result",result);// System.out.println(result);                               

                             JSONArray resultArray=new JSONObject(result).getJSONArray("d"); //獲取ModelUser類型的JSON對象數組 

                             TextView tv=(TextView)findViewById(R.string.textview1); 

                             tv.setText(((JSONObject)resultArray.get(0)).getString("UserName").toString()); //獲取resultArray第0個元素中的“UserName”屬性                            

                     }   

 

                     /*                    

             //2、調用帶參數的WebMethod

             final String SERVER_URL = "https://192.168.1.122:8082/WebServices/TestService.asmx/GetUserByUserName"; // 帶參數的WebMethod  

             HttpPost request = new HttpPost(SERVER_URL); // 根據內容來源地址創建一個Http請求  

                     request.addHeader("Content-Type", "application/json; charset=utf-8");//必須要添加該Http頭才能調用WebMethod時返回JSON數據             

             JSONObject jsonParams=new JSONObject();

                     jsonParams.put("strUserName", "wa1");//傳參,如果想傳遞兩個參數則繼續添加第二個參數jsonParams.put("param2Name","param2Value")

                     HttpEntity bodyEntity =new StringEntity(jsonParams.toString(), "utf8");//參數必須也得是JSON數據格式的字符串才能傳遞到服務器端,否則會出現"{'Message':'strUserName是無效的JSON基元'}"的錯誤

                     request.setEntity(bodyEntity);

                     HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 發送請求並獲取反饋                    

                     // 解析返回的內容                      

                     if (httpResponse.getStatusLine().getStatusCode() !=404)  //StatusCode為200表示與服務端連接成功,404為連接不成功

                     {                  

                 //因為GetUserByUserName返回的是ModelUser,所以該數據的JSON格式為:

                 //{"d":{"__type":"Model.ModelUser","UserName":"wa1","Password":"123"}}

                             String result = EntityUtils.toString(httpResponse.getEntity()); 

                 Log.i("result",result);    

                             JSONObject resultJSON=new JSONObject(result).getJSONObject("d");//獲取ModelUser類型的JSON對象                           

                             TextView tv=(TextView)findViewById(R.string.textview1);

                             tv.setText(resultJSON.getString("UserName").toString());                

                 Log.i("resultJSON",resultJSON);                            

                     }  

             */                

                } catch (Exception e) {}   

        }}; 

        Button button = (Button) findViewById(R.id.button1); 

        button.setOnClickListener(listener); 

 

    } 

至此,客戶端訪問服務端的代碼已經完成。

摘自 呼嚕Zz~的專欄

發佈留言