public void ExecuteURL(ExecuteURLParameters option) { string retValue = string.Empty; // Used to store the return value Thread thread = new Thread(() => { ExecuteURLThread(option); }); myThreads.Add(thread); thread.Start(); }
/// <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(); }