1. Key code
1.1 Coroutine implementation
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class WebRequest : MonoBehaviour
{
/// <summary>
/// GET request
/// </summary>
/// <param name="url">Request address</param>
/// <param name="callback">Request completion callback</param>
public void Get(string url, Action<bool,string> callback)
{
StartCoroutine(CoroutineGetRequest(url, callback));
}
/// <summary>
/// POST request
/// </summary>
/// <param name="url">Request address</param>
/// <param name="postData">Uploaded data</param>
/// <param name="requestHeader">Request header [application/json]</param>
/// <param name="callback">Request completion callback</param>
/// application/json
public void Post(string url, string postData,string requestHeader,Action<bool,string> callback)
{
StartCoroutine(CoroutinePostRequest(url, postData,requestHeader,callback));
}
IEnumerator CoroutineGetRequest(string url,Action<bool,string> callback)
{
// Use UnityWebRequest to send a GET request
using UnityWebRequest request = UnityWebRequest.Get(url);
//Send the request and wait for the result
yield return request.SendWebRequest();
// Determine whether the request result is successful or not
if (request.result != UnityWebRequest.Result.Success)
{
// If the request is unsuccessful, the failure status and error information will be returned through the callback function.
callback?.Invoke(false, request.error);
}
else
{
// Get response message
string responseMessage = request.downloadHandler.text;
// Call the callback function and pass in true and the response message
callback?.Invoke(true, responseMessage);
}
}
IEnumerator CoroutinePostRequest(string url,string postData,string requestHeader,Action<bool,string> callback)
{
//Create UnityWebRequest instance
using UnityWebRequest request = new UnityWebRequest(url, "POST");
//Convert POST data to byte array
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(postData);
//Set the upload handler to UploadHandlerRaw
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
//Set the download handler to DownloadHandlerBuffer
request.downloadHandler = new DownloadHandlerBuffer();
//Set the Content-Type of the request header
request.SetRequestHeader("Content-Type", requestHeader);
//Send the request and wait for the result
yield return request.SendWebRequest();
// Determine whether the request result is successful or not
if (request.result != UnityWebRequest.Result.Success)
{
// If the request is unsuccessful, the failure status and error information will be returned through the callback function.
callback?.Invoke(false, request.error);
}
else
{
// The request is successful, and the success status and response message are returned through the callback function
string responseMessage = request.downloadHandler.text;
callback?.Invoke(true, responseMessage);
}
}
}
1.2 Native C# implementation
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class WebRequest
{
#region Asynchronous request
/// <summary>
/// Asynchronous GET request
/// </summary>
/// <param name="url"></param>
/// <param name="requestComplete"></param>
/// <returns></returns>
public async void AsyncGet(string url, Action<bool, string> requestComplete)
{
var result =await AsyncGetRequest(url);
requestComplete?.Invoke(result.Item1, result.Item2);
}
/// <summary>
/// Asynchronous POST request
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="requestHeader"></param>
/// <param name="requestComplete"></param>
public async void AsyncPost(string url, string postData, string requestHeader, Action<bool, string> requestComplete)
{
var result = await AsyncPostRequest(url, postData, requestHeader);
requestComplete?.Invoke(result.Item1, result.Item2);
}
private static async Task<(bool, string)> AsyncGetRequest(string url)
{
var tcs = new TaskCompletionSource<(bool, string)>();
HttpClient client = new HttpClient();
try
{
//Send a GET request to get the response
HttpResponseMessage response = await client.GetAsync(url);
//If the response is successful
if (response.IsSuccessStatusCode)
{
// Read the response body and set the result to true and the response body
string responseBody = await response.Content.ReadAsStringAsync();
tcs.SetResult((true, responseBody));
}
//If the response fails
else
{
//Set the result to false and the response reason
tcs.SetResult((false, response.ReasonPhrase));
}
}
//Catch all exceptions and set the result to false and the exception message
catch (Exception ex)
{
tcs.SetResult((false, ex.Message));
}
// Regardless of whether an exception occurs, HttpClient resources are finally released.
finally
{
client.Dispose();
}
//Return the result of the asynchronous task
return await tcs.Task;
}
private async Task<(bool, string)> AsyncPostRequest(string url, string postData, string requestHeader)
{
//Create a TaskCompletionSource object to create tasks and set task results
var tcs = new TaskCompletionSource<(bool, string)>();
//Create an HttpClient object for sending HTTP requests
HttpClient client = new HttpClient();
try
{
//Create a StringContent object to set the request body content and encoding type
StringContent content = new StringContent(postData, Encoding.UTF8, requestHeader);
//Add a custom request header to the request header
client.DefaultRequestHeaders.Add("CustomHeader", requestHeader);
//Send a POST request and get the response result
HttpResponseMessage response = await client.PostAsync(url, content);
// Determine whether the request is successful
if (response.IsSuccessStatusCode)
{
//Read the returned content
string responseBody = await response.Content.ReadAsStringAsync();
//Set the task result of the TaskCompletionSource object to success and pass the returned content
tcs.SetResult((true, responseBody));
}
else
{
//Set the task result of the TaskCompletionSource object to failure and pass error information
tcs.SetResult((false, response.ReasonPhrase));
}
}
catch (Exception ex)
{
// When an exception occurs, set the task result of the TaskCompletionSource object to failure and pass the exception information
tcs.SetResult((false, ex.Message));
}
finally
{
// Release the resources of the HttpClient object
client.Dispose();
}
//Return the result of the asynchronous task
return await tcs.Task;
}
#endregion
}
2. Sample code
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
[SerializeField] private WebRequest webRequest;
private void Start()
{
GetData();
PostData();
}
void GetData()
{
webRequest.Get("https://api.52vmy.cn/api/wl/mingyan", (isComplete, message) =>
{
if(isComplete)
{
Debug.Log(message);
}
else
{
Debug.LogError(message);
}
});
}
void PostData()
{
Data postData = new Data()
{
word = "天"
};
string body = JsonUtility.ToJson(postData);
webRequest.Post($"https://api.pearktrue.cn/api/word/parse.php",body,"application/json", (isComplete,message) =>
{
if(isComplete)
{
Debug.Log(message);
}
else
{
Debug.LogError(message);
}
});
}
[System.Serializable]
private class Data
{
public string word;
}
}
3. Operation results