您当前的位置: 首页 >  网络

CoderZ1010

暂无认证

  • 3浏览

    0关注

    168博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

UnityWebRequest 通过Post方式发起网络请求

CoderZ1010 发布时间:2021-10-20 15:15:14 ,浏览量:3

以实际工作中与后端人员对接接口为例,下图为后端人员提供的需要对接的某个接口:    

可见数据结构中包含了4个string类型的字段,首先定义数据结构,注意字段名和字段类型需要保持一致,否则导致无法正确解析数据。

/// 
/// 确认过闸
/// 
[Serializable]
public class Affirm
{
    public string id;
    public string inId;
    public string time;
    public string batchCode;
}

Serializable特性表示该类可序列化,否则无法进行序列化

    设置请求头header的Content-Type,它有四种类型:

        application/x-www-form-urlencoded(默认)  

        application/xml

        application/json

        multipart/form-data

由于该接口所传的参数为json格式,所以需要设置为application/json,否则导致报错:HTTP/1.1 415 Unsupported Media Type,下面封装发起网络请求的携程函数:

public IEnumerator SendWebRequest()
{
    //接口地址
    string url = "http://**.**.***.***:****/********/*****";
    //post数据 通过序列化获得字符串
    string postData = JsonMapper.ToJson(new Affirm());
    //Post网络请求
    using (UnityWebRequest request = UnityWebRequest.Post(url, UnityWebRequest.kHttpVerbPOST))
    {
        byte[] postBytes = Encoding.UTF8.GetBytes(postData);
        request.uploadHandler = new UploadHandlerRaw(postBytes);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        if (!request.isNetworkError && !request.isHttpError)
        {
            Debug.Log(response);
        }
        else
        {
            Debug.LogError($"发起网络请求失败: 确认过闸接口 -{request.error}");
        }
    }
}

当后端返回数据时,通过反序列化得到我们所需的Response类

[Serializable]
public class AffirmResponse
{
    public string msg;
    public int code;
    public bool hit;
    public List data;
}
public IEnumerator SendWebRequest()
{
    //接口地址
    string url = "http://**.**.***.***:****/********/*****";
    //post数据 通过序列化获得字符串
    string postData = JsonMapper.ToJson(new Affirm());
    //Post网络请求
    using (UnityWebRequest request = UnityWebRequest.Post(url, UnityWebRequest.kHttpVerbPOST))
    {
        byte[] postBytes = Encoding.UTF8.GetBytes(postData);
        request.uploadHandler = new UploadHandlerRaw(postBytes);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        if (!request.isNetworkError && !request.isHttpError)
        {
            //反序列化
            var response = JsonMapper.ToObject(request.downloadHandler.text);
            Debug.Log($"Code:{response.code}  Msg:{response.msg}  Hit:{response.hit}");
        }
        else
        {
            Debug.LogError($"发起网络请求失败: 确认过闸接口 -{request.error}");
        }
    }
}
关注
打赏
1653184800
查看更多评论
立即登录/注册

微信扫码登录

0.0507s