標籤:android style blog http io ar color os sp
一 、伺服器端設定
1.修改web.config
在web.config裡面的的system.Web節點添加
<webServices>
<protocols>
<add name= "HttpPost"/>
<add name= "HttpGet"/>
</protocols>
</webServices>
2.修改XX.asmx.cs
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService]
//至此,一般函數可在android中可以通過代碼返回json資料,返回datatable的函數不可以
3.返回datatable的函數修改
此處需要用到一個函數將datatable轉換成json格式
#region dataTable轉換成Json格式 /// /// dataTable轉換成Json格式 /// /// /// public string DataTableJson(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{""); jsonBuilder.Append(dt.TableName.ToString()); jsonBuilder.Append("":["); for (int i = 0; i < dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("":""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("","); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); jsonBuilder.Append("}"); return jsonBuilder.ToString(); }
#endregion
再將原本需要返回datatable的函數建立一個類似函數。此處注意,一定要寫
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)],不然android在擷取資料時系統又會將轉換好的json資料再加一層json。 比如
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Xml)] public string HPReadQueryPhone(string strSql, string BD) { try { MSQuery dbTable = new MSQuery(); DataSet dsTable = dbTable.HPReadQuery(strSql, BD); dbTable = null; if (dsTable.Tables.Count == 0) { return ""; } else { return DataTableJson(dsTable.Tables[0]); } } catch (System.Exception err) { ThrowException(err); return null; } }
二、android代碼寫法
try{ String SERVER_URL = "http://192.168.10.33:81/MobileService/MSServiceQuery.asmx/HPReadQueryPhone"; 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("strdate", "1"); // jsonParams.put("aa", "1"); jsonParams.put("strSql", "select * from RRUser");//傳參,如果想傳遞兩個參數則繼續添加第二個參數jsonParams.put("param2Name","param2Value") jsonParams.put("BD", "27"); HttpEntity bodyEntity =new StringEntity(jsonParams.toString(), "utf8");//參數必須也得是JSON資料格式的字串才能傳遞到伺服器端,否則會出現"{‘Message‘:‘strUserName是無效的JSON基元‘}"的錯誤 Log.i("ex",jsonParams.toString()); request.setEntity(bodyEntity); HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 發送請求並擷取反饋 ShowMessage(httpResponse.getStatusLine().toString()); if(httpResponse.getStatusLine().getStatusCode()==200) { String result = EntityUtils.toString(httpResponse.getEntity()); Log.i("ex", result); ShowMessage(result); if(!result.equals("")) { try { JSONArray jsonObjs = new JSONObject (result).getJSONArray("Table"); JSONObject jsonObj = ((JSONObject)jsonObjs.opt(0)); String username=jsonObj.getString("UserCname"); ShowMessage(username);
Log.i("ex",String.valueOf(jsonObjs.length())+"aa");
} catch(JSONException e) { ShowMessage("資料錯誤"); } } } else { ShowMessage("網路傳輸錯誤"); } } catch(Exception e) { Log.i("ex", e.getMessage()); }
asp.net中webservice與android的json資料互動方式設定