public void LuaPost(string url, Action<object,object,object> callback, string fields = null, bool isEncodFields = true, string header = null, int timeout = 5)
{
StartCoroutine(_Post(url, delegate(long code, HttpHelperRequests requests, HttpHelperResponses rsponse)
{
callback?.Invoke(code, requests, rsponse);
}, fields, isEncodFields, header, timeout));
}
IEnumerator _Post(string url, HttpHelperPostGetCallbacks callback, string fields, bool isEncodFields, string header, int timeout)
{
using (UnityWebRequest webRequest = UnityWebRequest.Post(url, fields))
{
webRequest.timeout = timeout;
//设置请求头 根据实际需求来
webRequest.SetRequestHeader("Authorization", "");
//处理请求头设置
if (!string.IsNullOrEmpty(header))
{
JObject json = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(header);
if (json != null)
{
foreach (KeyValuePair<string, JToken> item in json)
{
webRequest.SetRequestHeader(item.Key, item.Value.Value<string>());
}
}
}
//不自动encode
if (!string.IsNullOrEmpty(fields) && !isEncodFields)
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(fields);
if (bodyRaw != null)
webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
}
//开始与远程服务器通信
//等待通行完成
yield return webRequest.SendWebRequest();
//组装请求信息
HttpHelperRequests requests = new HttpHelperRequests();
requests.url = url;
requests.fileds = fields;
requests.headers = header;
//组装返回信息
HttpHelperResponses responses = new HttpHelperResponses();
responses.code = webRequest.responseCode;
responses.message = webRequest.error;
responses.headers = webRequest.GetResponseHeaders();
responses.text = webRequest.downloadHandler.text;
responses.bytes = webRequest.downloadHandler.data;
//调用委托
callback?.Invoke(webRequest.responseCode, requests, responses);
//结束 处理占用资源
//尽快停止UnityWebRequest
webRequest.Abort();
//默认值是true,调用该方法不需要设置Dispose(),Unity就会自动在完成后调用Dispose()释放资源。
webRequest.disposeDownloadHandlerOnDispose = true;
//不再使用此UnityWebRequest,并应清理它正在使用的任何资源
webRequest.Dispose();
}
}
注:请求体不使用encode,重新赋值webRequest.uploadHandler即可。有的服务器计算sing时可能用非encode的串计算