/// <summary> /// 执行请求(异步) /// </summary> /// <param name="url">请求地址</param> /// <param name="data">请求参数</param> /// <param name="httpType">请求类型:POST、GET</param> /// <param name="headerParams">请求header</param> /// <returns></returns> private static async Task <string> ExecuteAsync(string url, string data, HTTP_TYPE httpType, Dictionary <string, string> headerParams, string contentType = null) { string strResult = string.Empty; url = httpType == HTTP_TYPE.POST ? url : string.Concat(url, "?", data); if (url.StartsWith("https://")) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;; try { StringBuilder strHeaders = new StringBuilder(); if (null != headerParams) { //加入头信息 foreach (var item in headerParams) { if (null == item.Key || string.IsNullOrWhiteSpace(item.Key)) { continue; } strHeaders.Append($"{item.Key}={item.Value}"); request.Headers.Add(item.Key, item.Value); } } //写数据 request.Method = httpType.ToString(); request.ContentType = contentType ?? CONTENT_TYPE; request.Accept = ACCEPT; request.Timeout = TIME_OUT; request.Headers.Set("Cache-Control", "no-cache"); if (httpType == HTTP_TYPE.POST) { byte[] bytes = Encoding.UTF8.GetBytes(data); request.ContentLength = bytes.Length; using var reqstream = request.GetRequestStream(); reqstream.Write(bytes, 0, bytes.Length); } using var response = (HttpWebResponse) await request.GetResponseAsync(); using var streamReceive = response.GetResponseStream(); using var streamReader = new StreamReader(streamReceive, Encoding.UTF8); strResult = await streamReader.ReadToEndAsync(); return(strResult); } catch (Exception ex) { throw ex; } finally { if (null != request) { request.Abort(); } } }
public void SentHttpRequre(HTTP_TYPE type, MessageHandler action) { StartCoroutine(SendGet(Url.GetUrl(type), action)); }