Xamarin.Forms-webservices访问
虽然xamarin.android/ios 均支持右键添加web引用方式引用webservices,但是xamarin.forms不支持此方式,而如果android/ios各做一套采用抽象方式实现则工程巨大,且耦合性太强。故决定采用http方式请求webservices。
废话不说上干货:
Webservices 端改造
- [System.Web.Script.Services.ScriptService]为支持jquery 或者 其他 http 调用必须放开注释,如没有此特性将不能调用;
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)] webservices 默认返回xml格式 为了增加 json格式返回增加此特性;
- UseHttpGet = true 特别注意此点增加此特性则允许httpget访问,不增加则只允许post访问此为单向指定。
建议 如果指定需要参数传递的方法建议使用post方式如果使用get方式会各种报错如 无效的json基元、参数'xx'缺少值。当然首先你要确认你的 jquery data 格式正确。
测试代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
namespace NeuHuiju.APF.MES.WebUI
{
/// <summary>
/// WebService_wzc 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService_wzc : System.Web.Services.WebService
{
/// <summary>
/// 有参方法POST请求支持
/// </summary>
/// <param name="lan"></param>
/// <returns></returns>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(string lan)
{
if (lan != "")
return lan.ToString();
else
return "Hello World";
}
/// <summary>
/// 无参方法 GET请求支持
/// </summary>
/// <returns></returns>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string World()
{
return "ceshi";
}
}
}
Web.config改造
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
<add name="HttpSoap"/>
<add name="Documentation"/>
</protocols>
</webServices>
增加webservices的请求支持。允许采用httpget、httppost方式
<system.webServer>
<handlers>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add
name="ScriptResource"
verb="GET,HEAD"
path="ScriptResource.axd"
preCondition="integratedMode"
type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
增加webservices的请求支持。此节点为System.Web.Script.Services.ScriptService提供支持 如缺少会报错。大多数500错误均可以检查此节点是否添加。
要求iis采用集成模式,不能使用经典。 (如果2.0)
Web端调试 jquery
为了便于测试新建html页面用于监控请求与返回。(为便于调试整理html代码用于测试,html必须与webservices同项目,否则会有跨域访问的问题。调试浪费精力。)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题页</title>
<script src="Script/jquery-1.4.1.js" type="text/javascript"></script>
</head>
<body>
<input type="button" id="ipt1" value="有参数调用" /><input type="text" id="canshu" />
<input type="button" id="Button1" value="无参数调用" />
<script type="text/javascript">
function GetInfo() {
$.ajax({
url: "Webservice/MES/WebService_wzc.asmx/HelloWorld",
contentType: "application/json; charset=gb2312",
dataType: "json",
type: "POST",
data:"{lan:'"+$('#canshu').val()+"'}",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
}
function GetWord() {
$.ajax({
url: "Webservice/MES/WebService_wzc.asmx/World",
contentType: "application/json; charset=gb2312",
dataType: "json",
type: "GET",
//data:"{lan:'"+$('#canshu')+"'}",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
}
$('#ipt1').click(function () {
var res = GetInfo();
});
$('#Button1').click(function () {
var res = GetWord();
});
</script>
</body>
</html>
Webclient类
using BarCode;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
namespace BarCode.Droid
{
/// <summary>
/// webclient帮助类
/// </summary>
public class WebClient_clr : IWebClient_clr
{
public WebClient_clr()
{
}
/// <summary>
/// 根据参数集合拼凑json提交字符串
/// </summary>
/// <param name="datas"></param>
/// <returns></returns>
private string CreateDataJson(IDictionary<string, object> datas = null)
{
if (datas == null)
return string.Empty;
var namevalues = datas.Select(d =>
string.Format(@"""{0}"":{1}"
, d.Key
, d.Value.GetType().IsValueType
? string.Format(@"""{0}""", (d.Value??"").ToString())
: this.ObjectToJson(d.Value))
).ToArray();
return string.Format("{{{0}}}", string.Join(",", namevalues));
}
public T WebRequest<T>(Uri uri, IDictionary<string, object> datas = null, string method = "POST", string charset = "UTF8")
{
string data = this.CreateDataJson(datas);
using (WebClient webClient = new WebClient())
{
//webClient.Encoding = (Encoding)Enum.Parse(typeof(Encoding), charset);
webClient.Headers["Method"] = method.ToString();
webClient.Headers["Content-Type"] = string.Format(@"application/json;charset={0}", charset);
string dwstring;
if ("POST".Equals(method))
dwstring = webClient.UploadString(uri, method, data);
else
dwstring = webClient.DownloadString(uri);
return JsonConvert.DeserializeObject<T>(dwstring);
}
}
/// <summary>
/// 异步调用返回结果
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="datas"></param>
/// <param name="method"></param>
/// <param name="charset"></param>
/// <returns></returns>
public async System.Threading.Tasks.Task<T> WebRequestAsync<T>(Uri uri, IDictionary<string, object> datas = null, string method = "POST", string charset = "UTF8")
{
string data = this.CreateDataJson(datas);
using (WebClient webClient = new WebClient())
{
//webClient.Encoding = (Encoding)Enum.Parse(typeof(Encoding), charset);
webClient.Headers["Method"] = method.ToString();
webClient.Headers["Content-Type"] = string.Format(@"application/json;charset={0}", charset);
string dwstring;
if ("POST".Equals(method))
dwstring = await webClient.UploadStringTaskAsync(uri, method, data);
else
dwstring = await webClient.DownloadStringTaskAsync(uri);
return JsonConvert.DeserializeObject<T>(dwstring);
}
}
public void WebRequestCompleted<T>(Uri uri, IDictionary<string, object> datas = null, string method = "POST", string charset = "UTF8", Action<T> RunT = null)
{
string data = this.CreateDataJson(datas);
using (WebClient webClient = new WebClient())
{
//webClient.Encoding = (Encoding)Enum.Parse(typeof(Encoding), charset);
webClient.Headers["Method"] = method.ToString();
webClient.Headers["Content-Type"] = string.Format(@"application/json;charset={0}", charset);
if ("POST".Equals(method))
{
webClient.UploadStringCompleted += (sender, e) =>
{
var dwstring = e.Result;
if (RunT != null)
RunT(JsonConvert.DeserializeObject<T>(dwstring));
};
webClient.UploadStringAsync(uri, method, data);
}
else
{
webClient.DownloadStringCompleted += (sender, e) =>
{
var dwstring = e.Result;
if (RunT != null)
RunT(JsonConvert.DeserializeObject<T>(dwstring));
};
webClient.DownloadStringAsync(uri);
}
}
}
#region 字符串对象序列化--ObjectConvertJson
/// <summary>
/// 字符串对象序列化
/// </summary>
/// <param name="jsonstr"></param>
/// <returns></returns>
public T ObjectConvertJson<T>(string jsonstr)
{
try
{
if (string.IsNullOrEmpty(jsonstr) || jsonstr == "{}" || jsonstr == "Token String in state Start would result in an invalid JavaScript object.")
return default(T);
if (!typeof(T).Name.Equals("Object"))//不等于动态类型
return JsonConvert.DeserializeObject<T>(jsonstr);
return default(T);
}
catch (Exception ex)
{
Debug.Print(ex.Message);
throw new NotImplementedException(jsonstr + "\r\n+" + ex.Message);
}
}
#endregion
#region 对象序列化json-ObjectToJson
/// <summary>
/// ObjectToJson 对象序列化 返回json
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string ObjectToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
#endregion
}
}
调用
string turl = url + "/GetServiceDateTime";
string sss = CommCLR.webclient.WebRequest<string>(new Uri(turl), method: "GET");//url,get方式获取string
//post方式提交 参数,key同web function 参数名
string sapurl = url + "/GetPOInforFromSAP";
IDictionary<string, object> datas = new Dictionary<string, object >();
datas.Add("plantNo", "1000");
datas.Add("poNo", "4500000060");
datas.Add("itemNo", new UserDto
{
Location = "11",
PlantNo = "1000"
});
var strss = CommCLR.webclient.WebRequest<string>(new Uri(sapurl), datas);