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("发送成功");
    }
}

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

相关推荐
专注VB编程开发20年5 分钟前
Vscode调试是真不方便
网络·网络协议
Yang96111 小时前
鼎讯 CM-K60 光缆普查仪:铁路高速光缆识别利器
网络
Qt程序员1 小时前
突破I/O天花板:Linux零拷贝技术
网络·linux内核·io·linq·零拷贝·mmap
mobai71 小时前
frr使用Valgrind定位内存泄漏
网络协议
HackTwoHub1 小时前
AI提示词注入绕过工具:一键绕过Codex/Claude安全限制,CTF夺旗与渗透测试必备神器
网络·人工智能·安全·web安全·系统安全·网络攻击模型·安全架构
sensen_kiss1 小时前
CAN302 Technologies for E-Commerce 电子商务技术 Pt.8 网络安全(Secure the Web)
网络·学习·安全·web安全
集远通信2 小时前
公路交通基础设施数字化转型升级-隧道北斗定位系统解决方案
网络·5g
其实防守也摸鱼2 小时前
Sqlmap:选取sqli-labs中less-8进行sqlmap注入测试
前端·css·网络·安全·web安全·less·sqli-labs
智慧光迅AINOPOL3 小时前
全光网行业选型指南:如何选择适合你的全光网解决方案
网络·全光网解决方案·全光网·校园全光网·校园全光网解决方案
wangjialelele3 小时前
Linux SystemV 消息队列 + 责任链模式:实现客户端消息处理流水线
linux·服务器·c语言·网络·c++·责任链模式