Unity 使用UnityWebRequest进行Get/Post请求

Unity 使用UnityWebRequest进行Get/Post请求

1、请求服务器链接

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class URL : MonoBehaviour
{
    string GetURL = "http://edu.xiaotu.cn/index/Unityapi/getUserInfo";
    string PostURL = "http://edu.xiaotu.cn/index/Unityapi/sendCourseInfo";

    private void Start()
    {
      //  StartCoroutine(Get_Demo());
        StartCoroutine(Post_Demo());
    }
    public IEnumerator Get_Demo()
    {
        UnityWebRequest webRequest = UnityWebRequest.Get(GetURL);
        //发送请求
        yield return webRequest.SendWebRequest();
        //等待请求完成
        while (!webRequest.isDone)
        {
            yield return null;
        }
        if (string.IsNullOrEmpty(webRequest.error))
        {//Get的请求成功//Get请求的返回参数
            var data = webRequest.downloadHandler.text;
            Debug.Log(data);
            Debug.Log("成功");

            UserInfo sg;
            sg = JsonUtility.FromJson<UserInfo>(data);

            Debug.Log(sg.uid+sg.err_msg);
            
        }
        else
        {//Get的请求失败
            Debug.Log("失败");
        }
    }

    public IEnumerator Post_Demo()
    {
        //Post请求的参数
        WWWForm form = new WWWForm();
        form.AddField("uid", "tea10000");
        form.AddField("course_id", "N700003");
        form.AddField("course_duration", "121212");
        form.AddField("course_score", "80");
        UnityWebRequest webRequest = UnityWebRequest.Post(PostURL, form);
        //发送请求
        yield return webRequest.SendWebRequest();
        if (string.IsNullOrEmpty(webRequest.error))
        {//Post的请求成功 //Post请求的返回参数
            var data = webRequest.downloadHandler.text;
              Debug.Log("成功:"+data);        }
        else
        {//Post的请求失败
            Debug.Log("失败");
        }
    }
}
public class UserInfo : Err
{
    public string uid;
    public string name;
    public int site_id;
}
public class Err
{
    public int err_no;
    public string err_msg;
}

2、请求本地json文件

using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// 读取本地Json题库并保存
/// </summary>
public class TikuTest : MonoBehaviour
{
    [HideInInspector]
    public Question_Info q;
    private void Awake()
    {
        StartCoroutine(GetData());
    }

    IEnumerator GetData()
    {
        var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "Tiku.json"));
        UnityWebRequest www = UnityWebRequest.Get(uri);
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log(www.downloadHandler.text);
            string jsonStr = www.downloadHandler.text;

            Question_Info ques = JsonMapper.ToObject<Question_Info>(jsonStr);
            q.question_number = ques.question_number;
            q.question_point = ques.question_point;
            for (int i = 0; i < ques.question_info.Count; i++)
            {
             q.question_info.Add(ques.question_info[i]);
            }
        }
    }
}
[System.Serializable]
public class Question_Info
{
    public int question_number;//题目数量
    public float question_point;//每题分值
    public List<TestData> question_info;
}
[System.Serializable]
public class TestData
{
    public int stide;//题号
    public string topic;//题目
    public string optionA;//选项A
    public string optionB;//选项B
    public string optionC;//选项C
    public string optionD;//选项D
    public string answer;//答案
}

3、post上传list类型

using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
/// <summary>
/// 接口对接
/// </summary>
public class TestURL : MonoBehaviour
{
 public void UploadScore_Btn0nClick()// 上传成绩
    { //for (int i = 0; i < 5; i++)
        //{
        //    string tt = UserTime(134);
        //    TExperimentalSteps te = new TExperimentalSteps(i, "步骤:" + i, "5", "10", "2", tt);
        //    step.Add(te);
        //}
        //port.experimentalSteps = step;
        if (!IsBusy)
        {
            IsBusy = true;

            Buzhou_UserTime();

            port.endTime = NowTime();
            port.timeUsed = UserTime(user_time);

            j = JsonUtility.ToJson(port);
            Debug.Log(j);
            byte[] postBytes = Encoding.Default.GetBytes(j);//把json格式的字符串转化成数组

            StartCoroutine(End_Post(postBytes));//发起请求
        }
    }
 IEnumerator End_Post(byte[] postBytes)
    {
        UnityWebRequest request = new UnityWebRequest(postURL, "POST");//method传输方式,默认为Get;

        request.uploadHandler = new UploadHandlerRaw(postBytes);//实例化上传缓存器
        request.downloadHandler = new DownloadHandlerBuffer();//实例化下载存贮器
        request.SetRequestHeader("Content-Type", "application/json");//更改内容类型,
        yield return request.SendWebRequest();//发送请求

        Debug.Log("Status Code: " + request.responseCode);//获得返回值
        IsBusy = false;
        if (request.responseCode == 200)//检验是否成功
        {
            string text = request.downloadHandler.text;//打印获得值
            Debug.Log("上传成绩成功" + text);
        }
        else
        {
            Debug.Log("上传成绩失败:" + request.responseCode);
        }
    }
}
[Serializable]
public class Port
{
    public string username;
    public long classId;
    public string studentId;
    public long experimentId;
    public string title;
    public int status;
    public int score;
    public int maxScore;
    public string startTime;
    public string endTime;
    public string timeUsed;
    public List<TExperimentalSteps> experimentalSteps = new List<TExperimentalSteps>();
}
[Serializable]
public class TExperimentalSteps
{
    public long stepSequence;
    public string stepTitle;
    public string stepScore;
    public string stepMaxscore;
    public string stepRepeatCount;
    public string stepTimeUsed;
    public TExperimentalSteps(long _stepSequence, string _stepTitle, string _stepScore, string _stepMaxscore, string _stepRepeatCount, string _stepTimeUsed)
    {
        this.stepSequence = _stepSequence;
        this.stepTitle = _stepTitle;
        this.stepScore = _stepScore;
        this.stepMaxscore = _stepMaxscore;
        this.stepRepeatCount = _stepRepeatCount;
        this.stepTimeUsed = _stepTimeUsed;
    }
}

4、Put修改

 public void Bianji_BtnOnClick()
    {
        YichangXiugai yx = new YichangXiugai();
        yx.id = xinxi_id;
        yx.deviceName= inputs[1].text;
        yx.alarmMsg= inputs[2].text;
        yx.alarmTime= inputs[4].text;
        string s = JsonUtility.ToJson(yx);Debug.Log("s:   "+s);
        StartCoroutine(Put_Times(s));
    }
 
   IEnumerator Put_Times(string s)
    {        UnityWebRequest webRequest = UnityWebRequest.Put(put_url, s);
        webRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        //发送请求
        yield return webRequest.SendWebRequest();
        //等待请求完成
        while (!webRequest.isDone)
        {
            yield return null;
        }
        if (string.IsNullOrEmpty(webRequest.error))
        {//Get的请求成功//Get请求的返回参数
         // var data = webRequest.downloadHandler.text;
            Debug.Log("修改成功");                  }
        else
        {//Get的请求失败
            Debug.Log("失败");
        }
    }

5、发布Android读取StreamingAssets下json文件

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

public class AndroidTest : MonoBehaviour
{
    public Text te;
    string filePath;
    void Start()
    {
        filePath = Path.Combine(Application.streamingAssetsPath, "config.json");
        StartCoroutine(Times());
    }
    IEnumerator Times()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            string androidFilePath = "jar:file://" + filePath;
            UnityWebRequest www = UnityWebRequest.Get(androidFilePath);
            yield return www.SendWebRequest();
            string jsonText = www.downloadHandler.text;
            te.text = jsonText;
            // 在这里处理你的JSON数据
            Item i = JsonUtility.FromJson<Item>(jsonText);
            te.text = i.Name;
        }
        // For other platforms
        else
        {
            string jsonText = File.ReadAllText(filePath);
            // 在这里处理你的JSON数据
        }
    }
}
[System.Serializable]
public class Item
{
   public string Name;
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ke-Di

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

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

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

打赏作者

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

抵扣说明:

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

余额充值