unity http post

  不带头的请求

public static IEnumerator SendPost( WWWForm _wForm, Action _callback, string interfaceName = "") {
        string url = string.Format("http://{0}:{1}/{2}?client=10",JT_Core.instance.ServerIP, JT_Core.instance.ServerPort, interfaceName);
            
        WWW postData = new WWW(url, _wForm);
        yield return postData;
        if (postData.error != null) {
            Debug.Log(postData.error);
        }
        else {
            _callback(postData.text);
        }
    }.

带头的post请求

    public static IEnumerator SendPostByWWW(string jsonStr, Action _callback, string interfaceName = null) {
        string url = string.Format("http://{0}:{1}/{2}", JT_Core.instance.ServerIP, JT_Core.instance.ServerPort, interfaceName);

        byte[] body = System.Text.Encoding.UTF8.GetBytes(jsonStr);

        Dictionary headerDic = new Dictionary();
        headerDic.Add("Authorization", "Token " + JT_PresonMessage.Token);
        //UnityEngine.Debug.Log(JT_PresonMessage.Token);

        WWW postData = new WWW(url, body, headerDic);
        yield return postData;
        if (postData.error != null) {
            Debug.LogError(postData.error);  
        }
        else {
            //Debug.Log("----->"+ postData.text);
            if (_callback != null) {
                _callback(postData.text);
            }
            
        }
    }


    这个没测试,上面两个都可以用

public static IEnumerator SendPostByWebRequest(string jsonStr,Dictionary headerDic,Action callback) {
        string url = string.Format("http://{0}:{1}/{2}?client=10", JT_Core.instance.ServerIP, JT_Core.instance.ServerPort, "");
        var request = new UnityWebRequest(url, "POST");

        byte[] postBytes = System.Text.Encoding.Default.GetBytes(jsonStr);

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

        List tmpKeys = new List();
        tmpKeys.AddRange(headerDic.Keys);
        for (int i = 0; i < tmpKeys.Count; i++) {
            request.SetRequestHeader(tmpKeys[i], headerDic[tmpKeys[i]]);
        }
        //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);
            callback(request.downloadHandler.text);
        }

    }

你可能感兴趣的:(Unity)