asp.net中webservice與android的json資料互動方式設定

來源:互聯網
上載者:User

標籤: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資料互動方式設定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.