一、首先有个我存东西发给他的结构
[System.Serializable]
public class LoginStruct
{
public string role;// 空 0 1 2
public string bumen;//5个部门
public string shenhezt;//0 第一页 其他都是1
}
二、通信代码 和处理
//-------------------------------------------引用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
//-------------------------------------------调用下面的方法(方便其他脚本调用)
public void diaoyong(string url, string postData)
{
StartCoroutine(SendJsonRequest(url,postData));
}
//-------------------------------------------方法
IEnumerator SendJsonRequest(string url, string postData) // ( url , json值)
{
using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
{
www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(postData));
//---------------------------------传输内容有汉字改了一下这个
www.SetRequestHeader("Content-Type", "application/json; charset=utf-8");
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
// Send the request and wait for the response
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Response: " + www.downloadHandler.text);
//-------------------------------------------------请求成功,处理相应数据
receive = www.downloadHandler.text;
}
}
}
三、调用
//----------------------------------------------------这里是另一页代码
public LoginStruct loginData;
private void Start()
{
loginData = new LoginStruct();
}
public void OnBtnClick(string bumenName)//点击部门按钮
{
//赋值
loginData.role = "";
loginData.bumen = bumenName;
loginData.shenhezt = "0";
string json = JsonUtility.ToJson(loginData);
//调用 上面那页代码的方法
this.gameObject.GetComponent<HTTPhi>().diaoyong("这里写服务器的URL噢",json);
}