Unity与PHP简易交互

发布于 2019-07-02  48 次阅读


包含了Get和Post方法.

using System.Collections;
using UnityEngine;
public class Testphp : MonoBehaviour
{
    string strpathId = "http://xxxxx/drug/details?id="; // Get
    string strpathName = "http://xxxxx/drug/search"; //Post
    MsgInfo msgInfo = new MsgInfo();   //信息类
    InputInfo inputInfo = new InputInfo();//信息类
    void Start()
    {
        //Get
        strpathId += "1";    
        StartCoroutine(OnGetIdInfo(strpathId)); 
        //Post
        string strcontent = "阿莫西林";
        StartCoroutine(OnGetNameInfo(strpathName, strcontent)); 
    }
    IEnumerator OnGetIdInfo(string url)
    {
        WWW www = new WWW(url);
        yield return www;
        if (www.error != null)
        {
            print("php请求错误: 代码为" + www.error);
        }
        else
        { 
            print("php请求成功" + www.text); 
            msgInfo =(MsgInfo) NewTonJsonHelper.DeserializeObject(www.text, typeof(MsgInfo)); 
            Debug.Log(msgInfo.Infor.Id);
        }
    }
    IEnumerator OnGetNameInfo(string url,string content)
    {
        WWWForm form = new WWWForm();
        form.AddField("name", content);
        WWW www = new WWW(url, form);
        yield return www;
        if (www.error != null)
        {
            print("php请求错误: 代码为" + www.error);
        }
        else
        {
            print("php请求成功" + www.text); 
            inputInfo = (InputInfo) NewTonJsonHelper.DeserializeObject(www.text, typeof(InputInfo));
            Debug.Log(inputInfo.Code);
            foreach (var item in inputInfo.Infor)
            {
                Debug.Log( item.Id + item.Name);
            } 
        } 
    } 
}

不积跬步,无以至千里;不积小流,无以成江海。