u3d上传json到php 并接收php发送的json


 

U3d代码

 class  UserInfo
{
    public string id;
    public string name;

    public UserInfo() { }
    public UserInfo(string id,string name)
    {
        this.id = id;
        this.name = name;
    }
}
public class TestHtml : MonoBehaviour {


    string url = "http://127.0.0.1/test.php";
    byte[] namebyte;
    void Awake()
    {

          //1.用这个构造函数的时候。class UserIfo 不能有pulic UserInfo(){}这个空的构造函数

        //UserInfo userinfo = new UserInfo("wu","wenbo");
        //string nameinfo = JsonMapper.ToJson(userinfo);
        2.用这个构造函数的时候。class UserIfo 需要有pulic UserInfo(){}这个空的构造函数
        UserInfo userinfo = new UserInfo();
        userinfo.id = "wu";
        userinfo.name = "wenbo";
        string nameinfo = JsonMapper.ToJson(userinfo);     
        StartCoroutine(UnityWebRequestPost(url, nameinfo, text => { Debug.Log(text); }));

    }
}
  IEnumerator UnityWebRequestPost(string url, string jsonStr, Action<string> textCallBack)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(jsonStr);
        UnityWebRequest request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST)
        {
            uploadHandler = new UploadHandlerRaw(bytes),
            downloadHandler = new DownloadHandlerBuffer()
        };
        request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        yield return request.SendWebRequest();
        if (request.isHttpError || request.isNetworkError)
        {
            Debug.LogError(request.error);
        }
        else
        {
             string result = request.downloadHandler.text;
             Debug.Log(result);
            // string ss = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data, 0, request.downloadHandler.data.Length - 0);
            JsonData objs = JsonMapper.ToObject(request.downloadHandler.text);
            Debug.Log(objs["id"]);
            Debug.Log(objs["name"]);
            Debug.Log(objs.ToJson());             
        }
    }

PHP代码

 

$data = file_get_contents('php://input');
echo $data;

 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/php/272669.html

(0)
上一篇 2022年7月9日 08:37
下一篇 2022年7月9日 08:37

相关推荐

发表回复

登录后才能评论