Unity发送Http

本篇实现在Unity中发送Http请求。

讲解Get,Post,用于在Unity中进行数据对接。

一、Get

cs 复制代码
IEnumerator Get()
{
    string url = "";//链接
    UnityWebRequest request = UnityWebRequest.Get(url);//创建UnityWebRequest实例并设置请求方式为Get
    yield return request.SendWebRequest();//等待响应后再运行
    if (request.isNetworkError || request.isHttpError)
    {
        //这里做响应失败的逻辑
    }
    else
    {
        //这里做响应成功的逻辑
    }
}

二、用Post传输json

cs 复制代码
IEnumerator Post()
{
    UnityWebRequest sendrequest = new UnityWebRequest(url,"POST");

    //编写Json文件,这里用字符串转换
    string Sessagejson = "{" +
        "\"" + "messages" + "\"" + ":" + "[" +
        "{" +
        "\"" + "role" + "\"" + ":" + "\"" + "user" + "\"" + "," +
        "\"" + "content" + "\"" + ":" + "\"" + inputField.text + "\"" +
        "}" +
        "]" +
        "}";
    byte[] SendJson = new UTF8Encoding().GetBytes(Sessagejson);//将字符串内容转换为字节数组
    sendrequest.uploadHandler = new UploadHandlerRaw(SendJson);//设置上传处理器
    sendrequest.downloadHandler = new DownloadHandlerBuffer();//设置下载处理器
    sendrequest.SetRequestHeader("Content-Type", "application/json");//设置请求头
    yield return sendrequest.SendWebRequest();//发送并等待响应后再继续
    if (sendrequest.result != UnityWebRequest.Result.ConnectionError && sendrequest.result != UnityWebRequest.Result.ProtocolError)
    {
        //这里使用正则表达式进行解析json文件
        string pattern2 = "\"result\":\"(.*?)\"";//result表示在json文本中找到result以及他的内容
        Match match2 = Regex.Match(sendrequest.downloadHandler.text, pattern2);//在返回的json内容中查找
        Debug.log(match2.Groups[1].Value);//将查找到的内容输出
    }
    else
    {
        Debug.LogError(sendrequest.error);
    }
    //最后释放资源  
    sendrequest.Dispose();
}

注意这里使用的正则表达式解析json的方法只适合简单结构的json文件,如果你有更复杂的需要解析请参考我其他篇章或查找其他资料。

三、用Post传输文件

cs 复制代码
IEnumerator UploadAttachment_Api()
{

    //这一部分先获取文件(因为这是在Unity导出Web后使用的,其中表格位于streamingAsset文件夹下)   
 
    //文件上传部分需要用户选择或从服务器获取,WebGL不允许访问本地文件
    string fileName = "LabReport.xlsx";  // 假设文件名为LabReport.xlsx
    byte[] filedata = null;
    // 使用 UnityWebRequest 获取文件(假设文件位于服务器)
    string fileUrl = Path.Combine(UnityEngine.Application.streamingAssetsPath, fileName);
    UnityWebRequest fileRequest = UnityWebRequest.Get(fileUrl);
    yield return fileRequest.SendWebRequest();
    filedata = fileRequest.downloadHandler.data;




    //这一部分开始发送表格文件
    string url = "http://srm.imut.edu.cn/api/uploadfile"; //设置链接
    WWWForm attachment_form = new WWWForm();//WWWForm是Unity提供的处理HTTP表单数据的类
    attachment_form.AddField("uniqid", uniqid);           // 上传参数,这里以uniqid为例
    
    attachment_form.AddBinaryData("file", filedata, fileName);//添加文件
    UnityWebRequest up_att_request = UnityWebRequest.Post(url, attachment_form);
    // 设置Authorization头
    up_att_request.SetRequestHeader("Authorization", accessToken);//根据实际情况填写
    yield return up_att_request.SendWebRequest();
    if (up_att_request.isNetworkError || up_att_request.isHttpError)
    {
        Debug.Log("发送失败");
    }
    else
    {
        Debug.Log("发送成功");
    }
}

结尾:代码解析都写到了代码后面。有任何错误请指出,补充请评论,看到会第一时间回复,谢谢。

相关推荐
YMWM_2 小时前
UDP协议详解:从原理到Python实践
网络·网络协议·udp
pengyi8710152 小时前
共享 IP 与独享 IP 怎么选?被封后升级方案避坑
网络·网络协议·tcp/ip
YuanDaima20482 小时前
Linux 进阶运维与 AI 环境实战:进程管理、网络排错与 GPU 监控
linux·运维·服务器·网络·人工智能
凯勒姆4 小时前
网工网络设备原理及配置
网络·智能路由器
上海云盾-小余4 小时前
网站恶意爬虫拦截策略:智能识别与封禁实操方案
网络·爬虫·安全·web安全
xhbh6664 小时前
网关端口映射和路由器端口转发有什么区别?配置要点全解析
运维·服务器·网络·智能路由器·端口映射·映射·无痕网关
半壶清水4 小时前
用P4 Tutorial、BMv2 和 Mininet‌解析网络第一集------模拟环境搭建
运维·服务器·网络·网络协议·tcp/ip
高翔·权衡之境5 小时前
主题10:实时性——硬实时与软实时
服务器·网络·驱动开发·信息与通信·智能硬件
BullSmall5 小时前
Promtheus和Alertmanager 之间是通过管理平面还是业务层面IP交互
网络协议·tcp/ip·平面
黄筱筱筱筱筱筱筱5 小时前
交换综合实验
网络