首页 > 其他分享 >unity xorpay使用HTTP中post方式请求调用接口

unity xorpay使用HTTP中post方式请求调用接口

时间:2023-04-07 09:34:15浏览次数:39  
标签:HTTP string request public unity xorpay new Post UnityWebRequest

结合:https://www.cnblogs.com/guangzhiruijie/p/16985533.html

unity自带的UnityWebRequest提供了构成 HTTP 请求和处理 HTTP 响应。

构造函数:

public UnityWebRequest(); public UnityWebRequest(Uri uri); public UnityWebRequest(string url); public UnityWebRequest(Uri uri, string method); public UnityWebRequest(string url, string method); public UnityWebRequest(string url, string method, DownloadHandler downloadHandler, UploadHandler uploadHandler); public UnityWebRequest(Uri uri, string method, DownloadHandler downloadHandler, UploadHandler uploadHandler);

简单的例子:

using FF = StarEngineTec.Generic.FormatFunc; 
string url="";//请求地址
string jsonData="";//需要上传的json数据 
IEnumerator UploadPost()
{
    UnityWebRequest uwr = new UnityWebRequest(url, "POST"); 
    uwr.uploadHandler = new UploadHandlerRaw(FF.StringToBytes(jsonData));
    uwr.downloadHandler = new DownloadHandlerBuffer(); 
    //如果有请求头,根据具体字段要求设置
    uwr.SetRequestHeader("Content-Type", "application/json");
    uwr.SetRequestHeader("app-version", "V1"); 
    yield return uwr.SendWebRequest(); 
    if (uwr.isHttpError || uwr.isNetworkError)
    {
         Debug.LogError("Login Error: " + uwr.error);
    }
}

其他常用方法:

public static UnityWebRequest Post(Uri uri, Dictionary<string, string> formFields); public static UnityWebRequest Post(Uri uri, WWWForm formData); public static UnityWebRequest Post(string uri, WWWForm formData); public static UnityWebRequest Post(Uri uri, string postData); public static UnityWebRequest Post(string uri, string postData); public static UnityWebRequest Post(string uri, Dictionary<string, string> formFields);
IEnumerator Upload(string str)
{
       WWWForm form = new WWWForm();
       form.AddField("data", str); 
       UnityWebRequest webRequest = UnityWebRequest.Post(url, form); 
       yield return webRequest.SendWebRequest(); 
       if (webRequest.isHttpError || webRequest.isNetworkError)
           Debug.Log(webRequest.error);
       else       
           Debug.Log(webRequest.downloadHandler.text);
}

一般上传完数据会返回条消息,可以根据code值判断成功与否,以及请求失败的原因

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,下面封装发起网络请求的携程函数:
/// <summary>
/// 确认过闸
/// </summary>
[Serializable]
public class Affirm
{
    public string id;
    public string inId;
    public string time;
    public string batchCode;
}
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<Affirm> 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<AffirmResponse>(request.downloadHandler.text);
            Debug.Log($"Code:{response.code}  Msg:{response.msg}  Hit:{response.hit}");
        }
        else
        {
            Debug.LogError($"发起网络请求失败: 确认过闸接口 -{request.error}");
        }
    }
}

 

标签:HTTP,string,request,public,unity,xorpay,new,Post,UnityWebRequest
From: https://www.cnblogs.com/guangzhiruijie/p/17294925.html

相关文章

  • UnityWebRequest-与后台数据传输Get/Post请求
    现在越来越多的项目都要用到登录、成绩上传等功能,涉及到Unity与后台接口之前调用与发送,下面着重介绍Unity自带的Http请求,包含Get/Post请求(表单、json、有头文件的请求。)一、Get请求直接填入接口地址,即可接收后台返回的json数据,新手在这里可能有点懵,不知道接口是什么意思,这里接口......
  • 跨域问题:Access to XMLHttpRequest at......
    前端代码报错,如图: 1、因本地不支持跨域,需要安装下【允许跨域的app】pipinstalldjango-cors-headers 2、回到Django项目中进入setting.pyINSTALLED_APPS:#我们创建了哪些子项目要在这里添加,不然如数据库的类不会帮创建INSTALLED_APPS=['django.contrib.admin'......
  • go net/http包的使用
    前言:Go语言标准库内建提供了net/http包,涵盖了HTTP客户端和服务端的具体实现。使用net/http包,我们可以很方便地编写HTTP客户端或服务端的程序。 正文:包的文档地址:https://go-zh.org/pkg/net/http net/http包使用说明:注册路由http.HandleFunc("/index",getHandle)  ......
  • 管理WEB服务器文件的WebDAV协议&HTTP大跃进--QUIC与HTTP30&WEB安全攻击概述
    管理WEB服务器文件的WebDAV协议WebADV协议    WEBDAV追加方法  WeDAV请求示例  HTTP大跃进--QUIC与HTTP30 QUIC&HTTP3.0   HTTP2.0的问题队头阻塞建立连接的握手延迟大QUIC的特性0RTT   没有队头阻塞的多路复用 ......
  • Unity Editor 编辑器开发全通关
     https://github.com/XINCGer/UnityToolchainsTrick    https://zhuanlan.zhihu.com/p/503154643......
  • HTTP JSON接口模拟工具interfake的使用(模拟接口返回json数据)
    场景在与第三方系统进行模拟对接时,需要本地根据接口文档的示例json数据快速模拟出来接口进行调试用。Interfake官方github地址:https://github.com/basicallydan/interfakeInterfake能简便地创建虚假的HTTPAPI,只需简单几行代码就可以创建模拟JSON接口(使用命令行方式也可以......
  • HTTPS双向认证【转】
    背景在三方接口对接中,偶尔会遇到需要传递证书的情况,这种方式其实是在SSL握手过程中会同时验证客户端和服务器的身份,这就是我们常说的 双向认证。双向认证需要服务器和客户端提供身份认证,只能是服务器允许的客户方能访问,安全性相对于要高一些。下面老黄用几个小例子来演示一下......
  • HTTP协议的瓶颈&双工通信的WebScocket与HTTP
    HTTP协议的瓶颈影响HTTP网络请求的因素1.带宽2.延迟 HTTP协议的瓶颈1.一条连接只可发送一个请求2.请求只能从客户端开始,客户端不可以接受除响应以外的指令3.请求/响应头部不经压缩就发送4.每次互相发送相同的头部造成的浪费较多5.非强制压缩发送 双工通信的WebScock......
  • 成功解决requests 报错raise SSLError(e, request=request)_requests.exceptions.SSL
    问题描述在使用requests调用https接口时,会遇到ssl证书报错raiseSSLError(e,request=request)requests.exceptions.SSLError:HTTPSConnectionPool(host='v4.ketangpai.com',port=443):Maxretriesexceededwithurl:/UserApi/login(CausedbySSLError(SSLCertVerificat......
  • http
    HTTP工作原理HTTP协议工作于客户端-服务端架构上。浏览器作为HTTP客户端通过URL向HTTP服务端即WEB服务器发送所有请求。HTTP三点注意事项:HTTP是无连接:无连接的含义是限制每次连接只处理一个请求,服务器处理完客户的请求,并收到客户的应答后,即断开连接,采用这种方式......