方式一 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”);来获取原始数据。给内存带来的压力较小。包括二进制文件流也可以