private static void HttpPost(string url, string body, string contenttype, HTTPCallback cb) { byte[] request_body = Encoding.UTF8.GetBytes(body); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); //request.Proxy = new WebProxy("127.0.0.1", 8888); request.Method = "POST"; request.ProtocolVersion = new Version(1, 1); request.UserAgent = "BeiJingJiaoJing/1.1.1 (iPhone; iOS 10.1.1; Scale/2.00)"; request.Accept = "application/json"; request.ContentType = contenttype; request.Headers.Add("Accept-Encoding", "gzip, deflate, br"); request.Headers.Add("Accept-Language", "zh-Hans-CN;q=1"); request.KeepAlive = true; request.ContentLength = request_body.Length; request.GetRequestStream().Write(request_body, 0, request_body.Length); request.BeginGetResponse((result) => { var response = request.EndGetResponse(result); var response_stream = response.GetResponseStream(); StreamReader reader = new StreamReader(response_stream, System.Text.Encoding.UTF8); string str = reader.ReadToEnd(); response.Close(); cb?.Invoke(str, null); }, request); } catch (WebException ex) { cb?.Invoke("", ex); } }
public RequestWithCB(WWW a_Request, HTTPCallback a_Callback, bool a_Important) { Request = a_Request; Callbacks = new List <HTTPCallback>(); Callbacks.Add(a_Callback); Important = a_Important; }
public static void Request(string a_URL, HTTPCallback a_Callback, bool a_Important) { for (int i = 0; i < m_Requests.Count; i++) { if (m_Requests[i].Request.url == a_URL) { m_Requests[i].Add(a_Callback); return; } } m_Requests.Add(new RequestWithCB(new WWW(a_URL), a_Callback, a_Important)); }
public void HttpGet(string url, string Referer, HTTPCallback cb) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = mCookiesContainer; request.Method = "GET"; request.ProtocolVersion = new Version(1, 1); request.UserAgent = "BeiJingJiaoJing/1.1.1 (iPhone; iOS 10.1.1; Scale/2.00)"; request.Headers.Add("Accept-Encoding", "gzip, deflate"); request.Headers.Add("Accept-Language", "zh-Hans-CN;q=1"); request.Referer = "https://api.jinjingzheng.zhongchebaolian.com/enterbj/platform/enterbj/loadotherdrivers"; request.KeepAlive = true; request.BeginGetResponse((result) => { var response = request.EndGetResponse(result); var response_stream = response.GetResponseStream(); var buf = ReadResponseStream(response_stream); response.Close(); cb?.Invoke(buf, null); }, request); } catch (WebException ex) { cb?.Invoke(null, ex); } }
public void Add(HTTPCallback a_RequestCallback) { Callbacks.Add(a_RequestCallback); }
/// <summary> /// Executes the URL Thread. /// </summary> /// <param name="option">Option.</param> private void ExecuteURLThread(ExecuteURLParameters option) { //MyDebug.Log("executing {0}", url); HttpWebResponse wRes = null; HttpWebRequest wReq; string rawData = string.Empty; Stream webResponseStream = null; StreamReader webResStreamReader = null; HTTPCallback callbacker = new HTTPCallback(); Response sr = new Response(); sr.error = null; try { callbacker._callback = option.callback; #region GET URL (No multopart and No Compression) if (!option.isMultipart || option.method.Equals(WebMethod.GET)) { if (null != option.postData && option.postData.Count > 0) { foreach (string s in option.postData.Keys) { rawData += s + "=" + WWW.EscapeURL(option.header[s].ToString()) + "&"; } rawData = rawData.TrimEnd('&'); } } if (option.method == WebMethod.GET && rawData.Length > 0) { if (!option.url.EndsWith("?", StringComparison.OrdinalIgnoreCase) && !option.url.Contains("?")) { option.url += "?"; } else if (!option.url.EndsWith("&", StringComparison.OrdinalIgnoreCase)) { option.url += "&"; } option.url += rawData; option.url = option.url.TrimEnd('&'); option.url = option.url.TrimEnd('?'); } //MyDebug.Log("executing {0}", url); #endregion #region Core part of Creating Request //MyDebug.Log("Createing Request for url: {0}", option.url); wReq = (HttpWebRequest)WebRequest.Create(option.url); wReq.ContentType = "text/plain"; //MyDebug.Log("Request created"); if (null != option.header && option.header.Count > 0) { //MyDebug.Log("Setting up Header data"); foreach (string s in option.header.Keys) { wReq.Headers.Add(s, option.header[s].ToString()); } } wReq.Credentials = CredentialCache.DefaultCredentials; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications); wReq.Timeout = option.timeOut; wReq.Method = option.method.ToString().ToUpper(); #endregion #region POST or Multipart Past //Stream stream; byte[] postData = null; //MyDebug.Log("Multipart: {0}, method: {1}", option.isMultipart, option.method); #region Non-multipart POST request if (!option.isMultipart && option.method.Equals(WebMethod.POST) && rawData.Length > 0) { MyDebug.Log("checking non multipart post data"); postData = _encoding.GetBytes(rawData); wReq.ContentType = "application/x-www-form-urlencoded"; wReq.ContentLength = postData.Length; } #endregion #region multipart POST Request if (option.isMultipart && option.method.Equals(WebMethod.POST)) { //MyDebug.Log("checking multipart post data"); string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); Stream fromStream = new MemoryStream(); fromStream = CreateMultipartFormData(fromStream, option.postData, formDataBoundary); //Add the end of the request. Start with a newline string footer = "--" + formDataBoundary + "--\r\n"; fromStream.Write(_encoding.GetBytes(footer), 0, _encoding.GetByteCount(footer)); fromStream.Position = 0; postData = new byte[fromStream.Length]; fromStream.Read(postData, 0, postData.Length); fromStream.Close(); wReq.Method = "POST"; wReq.ContentType = "multipart/form-data; boundary=" + formDataBoundary; wReq.ContentLength = postData.Length; } #endregion if (wReq.Method == "POST") { switch (option.compMode) { case Compression.Normal: //MyDebug.Log("Writing normal stream for post data"); using (var stream = wReq.GetRequestStream()) { stream.Write(postData, 0, postData.Length); } break; case Compression.GZip: //MyDebug.Log("Writing GZip stream for post data"); wReq.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip"); wReq.Headers.Add("Accept-Encoding", "gzip,deflate"); using (var stream = wReq.GetRequestStream()) { using (var zipStream = new GZipStream(stream, CompressionMode.Compress)) { zipStream.Write(postData, 0, postData.Length); } } break; case Compression.Deflate: //MyDebug.Log("Writing deflate stream for post data"); wReq.Headers.Add(HttpRequestHeader.ContentEncoding, "deflate"); wReq.Headers.Add("Accept-Encoding", "gzip,deflate"); using (var stream = wReq.GetRequestStream()) { using (var zipStream = new DeflateStream(stream, CompressionMode.Compress)) { zipStream.Write(postData, 0, postData.Length); } } break; } } #endregion //MyDebug.Log("Getting Response"); wRes = (HttpWebResponse)wReq.GetResponse(); callbacker.responseHeader = wRes.Headers; //MyDebug.Log("Getting stream from Response: {0}", wRes.ContentEncoding.ToString()); webResponseStream = wRes.GetResponseStream(); if (wRes.ContentEncoding.ToLower().Contains("gzip")) { //MyDebug.Log("UnCompressing GZip Stream"); webResponseStream = new GZipStream(webResponseStream, CompressionMode.Decompress); } else if (wRes.ContentEncoding.ToLower().Contains("deflate")) { //MyDebug.Log("UnCompressing Deflate Stream"); webResponseStream = new DeflateStream(webResponseStream, CompressionMode.Decompress); } //MyDebug.Log("Getting reader from stream"); webResStreamReader = new StreamReader(webResponseStream, Encoding.Default); //MyDebug.Log("Reading text from StreamReader"); callbacker.webResData = webResStreamReader.ReadToEnd(); //MyDebug.Log("data read end"); //MyDebug.Log("TEST DATA: {0}", sr1); //wRes.Close(); } catch (HttpListenerException hlex) { sr.status = false; sr.error = new Error(); sr.error.data = hlex.Data; sr.error.type = "HttpListenerException"; sr.error.errorCode = hlex.ErrorCode; sr.error.message = hlex.Message; sr.error.exceptionSource = hlex.Source; sr.error.helpLink = hlex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } catch (ProtocolViolationException pvex) { sr.status = false; sr.error.data = pvex.Data; sr.error.type = "ProtocolViolationException"; sr.error.errorCode = 0; sr.error.message = pvex.Message; sr.error.exceptionSource = pvex.Source; sr.error.helpLink = pvex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } catch (WebException wex) { sr.status = false; sr.error = new Error(); sr.error.data = wex.Data; sr.error.type = "WebException"; sr.error.errorCode = 0; sr.error.message = wex.Message; sr.error.exceptionSource = wex.Source; sr.error.helpLink = wex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } catch (Exception ex) { sr.status = false; sr.error = new Error(); sr.error.data = ex.Data; sr.error.type = "Exception"; sr.error.errorCode = 0; sr.error.message = ex.Message; sr.error.exceptionSource = ex.Source; sr.error.helpLink = ex.HelpLink; callbacker.webResData = Prime31.Json.encode(sr); } finally { if (wRes != null) { wRes.Close(); } if (webResponseStream != null) { webResponseStream.Close(); } if (webResStreamReader != null) { webResStreamReader.Close(); } wRes = null; webResponseStream = null; webResStreamReader = null; } //MyDebug.Log("Ready to ques"); //MyDebug.Warning("TEST {0}", callbacker.webResData); _mainThread.Enqueue(callbacker.ExecuteCallback); Thread.CurrentThread.Abort(); }
/// <summary> /// Uploads the file in thread. /// </summary> /// <param name="options">Options.</param> private void UploadFileInThread(UploadFileParameters options) { WebResponse wRes = null; HttpWebRequest wReq = null; Stream responseStream = null; StreamReader responseReader = null; HTTPCallback callbacker = new HTTPCallback(); Response sr = new Response(); sr.error = null; if (options.filesToUpload == null) { options.filesToUpload = new List <UploadFileInfo>(); } foreach (UploadFileList ufl in options.uploadList) { string fileName = GameAnax.Core.IO.File.GetFileNameFromURL(ufl.filePath); int fileNameLength = fileName.Length; int x = ufl.filePath.LastIndexOf(fileName, StringComparison.InvariantCulture); string path = ufl.filePath.Left(x); Debug.Log(path); if (!File.Exists(ufl.filePath)) { Debug.LogWarning(string.Format("{0} is not available at location {1}", fileName, path)); continue; } byte[] fileData = File.ReadAllBytes(ufl.filePath); options.filesToUpload.Add(new UploadFileInfo() { contentType = ufl.contentType, fileBytes = fileData, fileName = fileName, uniqueKey = ufl.key }); } try { callbacker._callback = options.callback; string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); wReq = (HttpWebRequest)WebRequest.Create(options.url); wReq.ContentType = "multipart/form-data; boundary=" + formDataBoundary; wReq.Method = "POST"; wReq.CookieContainer = new CookieContainer(); wReq.Credentials = CredentialCache.DefaultCredentials; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications); if (null != options.header && options.header.Count > 0) { foreach (string headrKey in options.header.Keys) { wReq.Headers.Add(headrKey, options.header[headrKey].ToString()); } } #region x Stream fromStream = new MemoryStream(); fromStream = CreateMultipartFormData(fromStream, options.postData, formDataBoundary); fromStream = CreateMultiPartFileData(fromStream, options.filesToUpload, formDataBoundary); // Add the end of the request. Start with a newline string footer = "--" + formDataBoundary + "--\r\n"; fromStream.Write(_encoding.GetBytes(footer), 0, _encoding.GetByteCount(footer)); fromStream.Position = 0; byte[] formData = new byte[fromStream.Length]; fromStream.Read(formData, 0, formData.Length); fromStream.Close(); wReq.ContentLength = formData.Length; using (var stream = wReq.GetRequestStream()) { stream.Write(formData, 0, formData.Length); } #endregion wRes = wReq.GetResponse(); callbacker.responseHeader = wRes.Headers; responseStream = wRes.GetResponseStream(); responseReader = new StreamReader(responseStream); callbacker.webResData = responseReader.ReadToEnd(); responseReader.Close(); } catch (HttpListenerException hlex) { sr.status = false; sr.error = new Error(); sr.error.data = hlex.Data; sr.error.type = "HttpListenerException"; sr.error.errorCode = hlex.ErrorCode; sr.error.message = hlex.Message; sr.error.exceptionSource = hlex.Source; sr.error.helpLink = hlex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } catch (ProtocolViolationException pvex) { sr.status = false; sr.error = new Error(); sr.error.data = pvex.Data; sr.error.type = "ProtocolViolationException"; sr.error.errorCode = 0; sr.error.message = pvex.Message; sr.error.exceptionSource = pvex.Source; sr.error.helpLink = pvex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } catch (WebException wex) { sr.status = false; sr.error = new Error(); sr.error.data = wex.Data; sr.error.type = "WebException"; sr.error.errorCode = 0; sr.error.message = wex.Message; sr.error.exceptionSource = wex.Source; sr.error.helpLink = wex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } catch (Exception ex) { sr.status = false; sr.error = new Error(); sr.error.data = ex.Data; sr.error.type = "Exception"; sr.error.errorCode = 0; sr.error.message = ex.Message; sr.error.exceptionSource = ex.Source; sr.error.helpLink = ex.HelpLink; callbacker.webResData = JsonUtility.ToJson(sr); } finally { if (wRes != null) { wRes.Close(); } if (responseReader != null) { responseReader.Close(); } if (responseStream != null) { responseStream.Close(); } wRes = null; responseReader = null; responseStream = null; } _mainThread.Enqueue(callbacker.ExecuteCallback); Thread.CurrentThread.Abort(); }
private IEnumerator MakeRequest(string url, string data, string authType, string authKey, HTTPCallback callback) { byte[] bData = System.Text.Encoding.UTF8.GetBytes(data); #if UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_2 || UNITY_4_0 || UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 // Using hashtable for compatibility with Unity < 4.5 Hashtable headers = new Hashtable(); #else Dictionary <string, string> headers = new Dictionary <string, string>(); #endif headers.Add("Content-Type", "application/json"); if (authType != null) { headers.Add(authType, authKey); } headers.Add("X-ReportErrorAsSuccess", "true"); headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); WWW www = new WWW(url, bData, headers); yield return(www); if (!String.IsNullOrEmpty(www.error)) { Debug.LogError(www.error); callback(null, www.error); } else { string response = www.text; callback(response, null); } }
private void InstPost(string url, string data, string authType, string authKey, HTTPCallback callback) { StartCoroutine(MakeRequest(url, data, authType, authKey, callback)); }
/// <summary> /// Sends a POST HTTP request /// </summary> public static void Post(string url, string data, string authType, string authKey, HTTPCallback callback) { PlayFabHTTP.instance.InstPost(url, data, authType, authKey, callback); }