Unity(二十二) C#与PHP服务器交互方式

方式一   WWWForm表单提交

IEnumerator WWWPost(string json)
    {
        
        WWWForm form = new WWWForm();
        //键值对
        form.AddField("key", json);
        
        //请求链接,并将form对象发送到远程服务器
        UnityWebRequest webRequest = UnityWebRequest.Post(url,form);

        yield return webRequest.SendWebRequest();
        if (webRequest.isHttpError || webRequest.isNetworkError)
        {
            Debug.Log(webRequest.error);
            //
        }
        else
        {
            Debug.Log("发送成功:" + webRequest.downloadHandler.text);
        }
    }

通过表单指定key,php端接收数据 $_POST['fieldname']

 

指定表单,UnityWebRequest指请求

 public IEnumerator WebRequestPost(string jsondata)
    {
        UnityWebRequest _request;
        var url =  "";
        byte[] databyte = Encoding.UTF8.GetBytes(jsondata);
        _request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
        
        _request.uploadHandler = new UploadHandlerRaw(databyte);
        _request.downloadHandler = new DownloadHandlerBuffer();

        //此处指定表单 wwwform
        _request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        yield return _request.SendWebRequest();
        Debug.Log(_request.responseCode);

        if (_request.isHttpError || _request.isNetworkError)
        {
            Debug.LogError(_request.error);
        }
        else
        {
            Debug.Log(_request.downloadHandler.text);
        }
    }

 

方式2:对于未指定 Content-Type 的POST数据,UnityWebRequest请求

public IEnumerator WebPostRequest(string _url, string jsonString)
    {
        string url = _url;
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                
            }
            else
            {
               
                
                    Debug.Log(webRequest.downloadHandler.text);
                }
            
        }
    }

php端使用file_get_contents("php://input") 获取原数据

对于未指定 Content-Type 的POST数据,则可以使用file_get_contents(“php://input”);来获取原始数据。给内存带来的压力较小。包括二进制文件流也可以

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值