在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防火牆的情況下區域網路內的用戶端是不能夠通過"http://192.168.1.122:8082"訪問到該網站的,會顯示“無法開啟網頁”的錯誤,因此更不可能通過“http://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 = "http://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.2cto.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 = "http://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 = "http://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~的專欄