Unity3D网络通讯(六)-- UnityWebRequest实现WebService通讯

时间:2022-07-25
本文章向大家介绍Unity3D网络通讯(六)-- UnityWebRequest实现WebService通讯,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

前面几篇文章把主要的网络通讯方式都已经讲完了,今天是这个系列的最后一讲,关于WebService的通讯,主要是现在这个也不是主流,但是像如果对数据交互的老系统中用过WebSerive的,我们还是简单讲一下。

WebService通讯

微卡智享

基本调用WebService有两种方式:

  1. 使用UnityWebRequest调用webService;
  2. 利用VS自带的 wsdl工具生成 .cs;

上面第二个方式例子应该也挺多的,这里我就不再讲了,这篇主要就是看看用第一种方式调用WebService。

使用细节

1、其实自己写Web Service 时候,你就会发现在Web Service 下就是各种方法。所以使用时候,url后面加上“/”+你写的方法,这样就是执行你相应的相应方法。

2、这里主要注意Get和Post两种方法的区别与使用:get 就是获得数据。post就是向webservice 传送数据。

代码演示

微卡智享

WebService端代码

新建一个WebServiceDemo,然后鼠标右键新建项中,添加一个Web服务(ASMX),上图中右边红框是我已经创建好的服务。

WeatherForecast类创建一个和第一章Asp.Net Core创建的WeatherForecast一样的,这样方便我们Unity调用,不用再多次创建了。

WebService用的是xml格式,不过为了配合Unity的Json,所以我们这里在Nuget组件中还是要添加NewtonsoftJson。

在WebServiceDemo.asmx中我们写入了两个方法,一个不带参数的方法HelloWorld(用Get调用),一个带参数的方法DealWeather(用Post调用)。这样我们简单的WebService就创建完成了,和Asp.Net Core的发布一样,也是先生成文件系统,然后在IIS中新建网站进行发布。

WebSerive的Config

发布后的WebService如果要用Http的Get和Post方法,还需要在Web.config中进行配置

需要在web.config的文件<system.web>的节点下增加

    <webServices>
       <protocols>
           <add name="HttpPost" />
           <add name="HttpGet" />
       </protocols>
    </webServices>

Unity调用WebService

微卡智享

01

创建布局

在我们的Unity项目中再增加两个Button,一个是WebService的Get方法,一个是WebService的Post方法。

UIScript的脚本中加入这两个按钮

然后把这两个按钮拖进我们定义的两个按钮中

02

WebService类

新建了一个WebService的类

因为都是用的UnityWebRequest的方式调用,所以Get方法其实和HttpRestful中的Get方法基本一致,都是用的协程的方式处理,上图中标红框中不一样是因为通过WebService返回的数据是xml格式的,在Unity中我就不做解析了,所以这里参数前面加了个!

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;
        }
    }

    #region Get请求
    /// <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);
            }
        }
    }
    #endregion


    #region POST请求
    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);
            }
        }
    }
    #endregion
}

03

调用方法

Get方式调用

//WebService Get
btnwsget.onClick.AddListener(() =>
{
    string url = "http://" + edtipadr.text + ":" + edtport.text + "/WebServicedemo.asmx/HelloWorld";
    WebService.Instance.Get(url, actionRes);
});

Post调用

//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);
});

实现效果