赞
踩
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using LitJson;
using static UnityEngine.Networking.UnityWebRequest;
/// <summary>
/// 获取后端接口的方法
/// </summary>
public class WebRequestSet : MonoBehaviour
{
public static string NetworkConfig = "";
public static string WeatherConfig = "api.map.baidu.com/weather/v1";
/// <summary>
/// Get方法
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static IEnumerator GetData(string url)
{
//2.创建一个UnityWebRequest类 method属性为Get
UnityWebRequest request = UnityWebRequest.Get(url);
//3.等待响应时间,超过5秒结束
request.timeout = 5;
//4.发送请求信息
yield return request.SendWebRequest();
//5.判断是否下载完成
if (request.isDone)
{
//6.判断是否下载错误
if (request.isHttpError || request.isNetworkError)
Debug.Log(request.error);
else
Debug.Log(request.downloadHandler.text);
}
}
/// <summary>
/// Post方法
/// </summary>
/// <returns></returns>
public static IEnumerator PostData(string config, WWWForm wForm = null)
{
string url;
if (config == "net")
{
url = "https://" + NetworkConfig;
}
else
{
url = "https://" + WeatherConfig;
}
//WWWForm form = new WWWForm();
键值对
//form.AddField("key", "value");
//form.AddField("name", "Chinar");
//请求链接,并将form对象发送到远程服务器
UnityWebRequest webRequest = UnityWebRequest.Post(url, wForm);
yield return webRequest.SendWebRequest();
if (webRequest.isDone)
{
if (webRequest.isHttpError || webRequest.isNetworkError)
{
Debug.Log(webRequest.error);
}
else
{
if (string.IsNullOrEmpty(webRequest.downloadHandler.text))
{
Debug.LogError("返回值为空");
}
else
{
Debug.Log(webRequest.downloadHandler.text);
}
}
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。