Unity 基础 之 UnityWebRequest Post 的简单封装使用

 Unity 基础 之 UnityWebRequest Post 的简单封装使用

一、简单介绍

Unity中的一些知识点整理。

本节简单介绍在Unity开发中的,使用 UnityWebRequest,进行 Post 请求,值得注意的是,根据不同的请求头,注意传入不同的数据格式就好,如果你有新的方式也可以留言,多谢。

具体可参见 Unity 官网 UnityWebRequest 介绍

Unity - Manual: UnityWebRequest

 


二、实现原理

1、UnityWebRequest(url, "POST") 进行 Post 请求

2、UnityWebRequest.uploadHandler = new UploadHandlerRaw(postBytes); //添加数据
      UnityWebRequest.downloadHandler = new DownloadHandlerBuffer(); // 数据Buffer
      UnityWebRequest.SetRequestHeader("Content-Type", requestHeaderStr);// 请求头设置

三、注意事项

1、注意请求头设置不同,传入的数据格式会有所区别

2、注意字符串转为字节数组

四、效果预览

五、实现步骤

1、打开Unity,新建工程

 

2、编写脚本,实现 UnityWebRequest  Post 功能

3、把 测试脚本挂载场景中

 

4、运行场景,效果如上

六、关键代码

1、TestUnityWebRequestPostSimpleWrapper

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace XANUtils.TestSpace
{ 

	public class TestUnityWebRequestPostSimpleWrapper : MonoBehaviour
	{
		// Start is called before the first frame update
		void Start()
		{
			Test();
		}

		void Test() {
			UnityWebRequestPostSimpleWrapper postSimpleWrapper = new UnityWebRequestPostSimpleWrapper(this);

			//请求头 Form 表单格式 Post
			postSimpleWrapper.StartUnityWebRequestPost("你的网址",
				"你的类似格式数据:password=12345",                       // 更加请求头不同,Post Data 数据不同
				"application/x-www-form-urlencoded",    // form 格式
				(isNotError,responseStr)=> {
					if (isNotError)
					{
						Debug.Log(GetType() + "/Test()/ responseStr : " + responseStr);
						Debug.Log(GetType() + "/Test()/ 解析 responseStr ... " );
					}
					else {
						Debug.Log(GetType() + "/Test()/ error : " + responseStr);
						Debug.Log(GetType() + "/Test()/ 针对报错,检查处理 ... ");
					}
				});

			//请求头 Json 表单格式 Post
			postSimpleWrapper.StartUnityWebRequestPost("你的网址",
				"你的类似格式数据:{\"password\":\"12345\"}", // 更加请求头不同,Post Data 数据不同
				"application/json",			// json 格式
				(isNotError, responseStr) => {
					if (isNotError)
					{
						Debug.Log(GetType() + "/Test()/ responseStr : " + responseStr);
						Debug.Log(GetType() + "/Test()/ 解析 responseStr ... ");
					}
					else
					{
						Debug.Log(GetType() + "/Test()/ error : " + responseStr);
						Debug.Log(GetType() + "/Test()/ 针对报错,检查处理 ... ");
					}
				});
		}
	}
}

2、UnityWebRequestPostSimpleWrapper

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace XANUtils { 

	public class UnityWebRequestPostSimpleWrapper 
	{
		private MonoBehaviour mMono;
		public UnityWebRequestPostSimpleWrapper(MonoBehaviour mono) {
			mMono = mono;
		}

		public Coroutine StartUnityWebRequestPost(string url, string postData, string requestHeaderStr, Action<bool, string> onPostCallback) {
            if (mMono==null)
            {
				Debug.LogError(GetType()+ "/StartUnityWebRequestPost()/ mMono can not be null");
				return null;
            }

			return mMono.StartCoroutine(UnityWebRequestPost(url, postData, requestHeaderStr, onPostCallback));
		}

		IEnumerator UnityWebRequestPost(string url, string postData,string requestHeaderStr, Action<bool,string> onPostCallback)
		{
			
			using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
			{
				Debug.Log(GetType() + "/UnityWebRequestPost()/ url : " + webRequest.url);
				Debug.Log(GetType() + "/UnityWebRequestPost()/ postData : " + postData);

				byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
				webRequest.uploadHandler = new UploadHandlerRaw(postBytes);
				webRequest.downloadHandler = new DownloadHandlerBuffer();
				webRequest.SetRequestHeader("Content-Type", requestHeaderStr); 

				yield return webRequest.SendWebRequest();
				string response = null;
				if (webRequest.isNetworkError || webRequest.isHttpError )
				{
					response = webRequest.error;
					Debug.LogError(GetType() + "/UnityWebRequestPost()/ error : " + webRequest.error);

					if (onPostCallback != null)
					{
						onPostCallback.Invoke(false, response);

					}
				}
				else
				{

					response = webRequest.downloadHandler.text;
					
					Debug.Log(GetType() + "/UnityWebRequestPost()/ success : " + response);

					if (onPostCallback != null)
					{
						onPostCallback.Invoke(true, response);

					}
				}
			}

		}
	}
}

Unity中的UnityWebRequest是一个用于处理网络请求的类,可以通过POST方法发送JSON数据。通过UnityWebRequest类,可以轻松地向服务器发送一个包含JSON数据的POST请求。要使用UnityWebRequest发送POST请求,首先需要创建一个包含JSON数据的字符串,然后将其转换为字节数组,并设置请求的Content-Type为"application/json"。接着,构建一个UnityWebRequest对象,设置其URL和请求方式为POST,并将JSON数据添加到请求中。最后,发送请求并等待服务器的响应。 以下是一个简单的示例代码: ```csharp string url = "http://example.com/api"; string jsonData = "{\"key1\": \"value1\", \"key2\": \"value2\"}"; byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData); UnityWebRequest request = new UnityWebRequest(url, "POST"); request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { Debug.LogError(request.error); } else { Debug.Log("Post successful!"); } ``` 上述代码中,我们首先创建了一个包含JSON数据的字符串jsonData,然后将其转换为字节数组bodyRaw。接着,我们创建了一个UnityWebRequest对象request,设置了请求的URL和方法,并将JSON数据添加到请求中。最后,通过SendWebRequest方法发送POST请求,并根据响应的结果做出相应的处理。这样,就可以使用UnityWebRequest来发送包含JSON数据的POST请求了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仙魁XAN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值