unity携带header发送POST请求

unity中的网络请求,最方便、常用的如下两种方法。分别实现GET/POST。实际设计项目时,基础的表单POST显得相对简陋,后端往往需要添加许多验证。本文就主要介绍这些情况下,携带header头发送Post请求的注意事项,案例中需要用到LitJson。

WWW www = new WWW(url); //GET
WWW www = new WWW(url, form); //POST

 

一、原生WWW方法。

需要说明一下,www的第四种重载,在许多博客包括官方示例里面都还是Hashtable,实际情况是在5.0以前已经使用Dictionary<string, string>了。

WWW www = new WWW(string url, byte[] body, Dictionary<string,string> header);

WWW因为许多局限性在将来也会逐渐被边缘化,比如API中form-data是无法带header的,必须转成二进制数据。后端也要把multipart/form-data改成application/json。

using System.Collections;
using UnityEngine;
using LitJson;

public class Example1 : MonoBehaviour
{
    string url = "http://localhost/demo.php";

    IEnumerator Start()
    {
        JsonData data = new JsonData();
        data["license"] = "17N6-UE25-3333-WSCH-LONG";
        byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());

        Dictionary<string, string> header = new Dictionary<string, string>();
        //header["Content-Type"] = "application/json"; //两种方法
        header.Add("Content-Type", "application/json"); 

        WWW www = new WWW(url, postBytes, header);
        yield return www;
        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.Log(www.error);
        }
        Debug.Log(www.text);
    }
}

二、原生UnityWebRequest,需要引用UnityEngine.Networking,也是未来的主流方法。

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using LitJson;

public class Example2 : MonoBehaviour
{
    string url = "http://localhost/demo.php";

    IEnumerator Start()
    {
        var request = new UnityWebRequest(url, "POST");
        JsonData data = new JsonData();
        data["license"] = "17N6-UE25-3333-WSCH-LONG";
        byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());

        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("CLEARANCE", "I_AM_ADMIN");

        yield return request.Send();

        Debug.Log("Status Code: " + request.responseCode);
        if (request.responseCode == 200)
        {
            string text = request.downloadHandler.text;
            Debug.Log(text);
        }
    }
}

三、使用UniWeb插件Post(确保项目中导入UniWeb)

using System.Collections;
using UnityEngine;
using LitJson;

public class Example3 : MonoBehaviour
{
    string url = "http://localhost/demo.php";

    IEnumerator Start()
    {
        // body部分
        JsonData data = new JsonData();
        data["license"] = "58V2E-CCKCJ-B8VSE-MEW9Y-ACB2K 5Z62E-79JDV-79NAM-ZGVE6-ARBWY";
        byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());
        HTTP.Request r = new HTTP.Request("POST", url, postBytes);

        // Header部分
        r.headers.Clear();
        r.headers.Add("Content-Type", "application/json");
        r.timeout = 3; //设定超时时间

        yield return r.Send();

        // 异常处理
        if (r.exception != null)
        {
            Debug.Log("post request error: " + r.exception.ToString());

            // 超时
            if (r.exception is System.TimeoutException)
            {
                Debug.Log("Request timed out.");
            }
            // 其他报错
            else
            {
                Debug.Log("Exception occured in request.");
            }
        }
        else if (r.response.status != 200)
        {
            Debug.Log("post request code:" + r.response.status);
        }
        // 成功
        else
        {
            Debug.Log("post Success!!");
            Debug.Log("returned data:" + r.response.Text);
        }
        // 完成通信
        Debug.Log("WWW Done. " + url);
    }
}

四、C#网络请求HttpWebRequest

using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
using LitJson;

public class wwwpost : MonoBehaviour
{
    static string url = "http://www.setsuodu.com/demo.php";

    void Start()
    {
        JsonData data = new JsonData();
        data["Token"] = "acdc";
        data["action"] = "get_config";
        data["userid"] = "10086";
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data.ToJson());

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = bytes.Length;
        request.Headers.Add("Auther", "user_id");

        using (Stream reqStream = request.GetRequestStream())
        {
            reqStream.Write(bytes, 0, bytes.Length);
        }

        //处理响应
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (Stream responseStm = response.GetResponseStream())
        {
            StreamReader redStm = new StreamReader(responseStm, Encoding.UTF8);
            string result = redStm.ReadToEnd();
            Debug.Log(result);
        }
    }
}

 

  • 6
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值