学更好的别人,
做更好的自己。
——《微卡智享》
前言
WebService通讯

微卡智享
基本调用WebService有两种方式:
使用UnityWebRequest调用webService;
利用VS自带的 wsdl工具生成 .cs;
使用细节
1、其实自己写Web Service 时候,你就会发现在Web Service 下就是各种方法。所以使用时候,url后面加上“/”+你写的方法,这样就是执行你相应的相应方法。
2、这里主要注意Get和Post两种方法的区别与使用:get 就是获得数据。post就是向webservice 传送数据。
代码演示

微卡智享
WebService端代码
WebSerive的Config
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>
Unity调用WebService

微卡智享
01
创建布局
02
WebService类
Post的方式和HttpRestful的方式就不一样了,这里调用WebService的Post方式,需要用WWWForm的类型传入。
WebService完整代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class WebService : MonoBehaviour
{
private static WebService _instance;
public static WebService Instance
{
get
{
if (_instance == null)
{
GameObject goRestful = new GameObject("WebService");
_instance = goRestful.AddComponent<WebService>();
}
return _instance;
}
}
/// <summary>
/// Get请求
/// </summary>
/// <param name="url"></param>
/// <param name="actionResult"></param>
public void Get(string url, Action<bool, string> actionResult = null)
{
StartCoroutine(_Get(url, actionResult));
}
private IEnumerator _Get(string url, Action<bool, string> action)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
string resstr = "";
if (request.isNetworkError || request.isHttpError)
{
resstr = request.error;
}
else
{
resstr = request.downloadHandler.text;
}
if (action != null)
{
action(!request.isHttpError, resstr);
}
}
}
public void Post(string url, WWWForm data, Action<bool, string> actionResult = null)
{
StartCoroutine(_Post(url, data, actionResult));
}
private IEnumerator _Post(string url, WWWForm data, Action<bool, string> action)
{
using (UnityWebRequest request = UnityWebRequest.Post(url, data))
{
yield return request.SendWebRequest();
string resstr = "";
if (request.isNetworkError || request.isHttpError)
{
resstr = request.error;
}
else
{
resstr = request.downloadHandler.text;
}
if (action != null)
{
action(!request.isHttpError, resstr);
}
}
}
}
03
调用方法
Get方式调用
//WebService Get
btnwsget.onClick.AddListener(() =>
{
string url = "http://" + edtipadr.text + ":" + edtport.text + "/WebServicedemo.asmx/HelloWorld";
WebService.Instance.Get(url, actionRes);
});
//WebService Post
btnwspost.onClick.AddListener(() =>
{
string url = "http://" + edtipadr.text + ":" + edtport.text + "/WebServicedemo.asmx/DealWeather";
WeatherForecast item = new WeatherForecast();
item.Summary = "Alvin";
item.Date = DateTime.Now;
item.TemperatureC = 10;
item.TemperatureF = 20;
string json = JsonUtility.ToJson(item);
WWWForm form = new WWWForm();
form.AddField("json", json);
WebService.Instance.Post(url, form, actionRes);
});
实现效果
完
扫描二维码
获取更多精彩
微卡智享

「 往期文章 」
Unity3D网络通讯(五)--Socket通讯之Udp通讯
本文分享自微信公众号 - 微卡智享(VaccaeShare)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
来源:oschina
链接:https://my.oschina.net/u/4582134/blog/4643316