// See http://stackoverflow.com/questions/12224602/a-method-for-making-http-requests-on-unity-ios // for persistence. // See http://18and5.blogspot.com.es/2014/05/mono-unity3d-c-https-httpwebrequest.html /// <summary> /// Web service request. /// </summary> /// /// <param name="requestSettings"> Options for controlling the operation. </param> /// <param name="requestResponse"> The request response. </param> public void WebServiceRequest(RequestSetttings requestSettings, out RequestResponse requestResponse) { requestResponse = WebServiceRequest(requestSettings); }
/// <summary> /// Web service request. /// </summary> /// /// <param name="requestSettings">Options for controlling the operation. </param> /// /// <returns> /// A RequestResponse. /// </returns> private RequestResponse WebServiceRequest(RequestSetttings requestSettings) { RequestResponse result = new RequestResponse(requestSettings); try { //! Might throw a silent System.IOException on .NET 3.5 (sync). ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestSettings.uri); request.Method = requestSettings.method; // Both Accept and Content-Type are not allowed as Headers in a HttpWebRequest. // They need to be assigned to a matching property. if (requestSettings.requestHeaders.ContainsKey("Accept")) { request.Accept = requestSettings.requestHeaders["Accept"]; } if (!String.IsNullOrEmpty(requestSettings.body)) { byte[] data = Encoding.UTF8.GetBytes(requestSettings.body); if (requestSettings.requestHeaders.ContainsKey("Content-Type")) { request.ContentType = requestSettings.requestHeaders["Content-Type"]; } foreach (KeyValuePair <string, string> kvp in requestSettings.requestHeaders) { if (kvp.Key.Equals("Accept") || kvp.Key.Equals("Content-Type")) { continue; } request.Headers.Add(kvp.Key, kvp.Value); } request.ContentLength = data.Length; // See https://msdn.microsoft.com/en-us/library/system.net.servicepoint.expect100continue(v=vs.110).aspx // A2 currently does not support this 100-Continue response for POST requets. request.ServicePoint.Expect100Continue = false; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); } else { foreach (KeyValuePair <string, string> kvp in requestSettings.requestHeaders) { if (kvp.Key.Equals("Accept") || kvp.Key.Equals("Content-Type")) { continue; } request.Headers.Add(kvp.Key, kvp.Value); } } WebResponse response = request.GetResponse(); if (response.Headers.HasKeys()) { foreach (string key in response.Headers.AllKeys) { result.responseHeaders.Add(key, response.Headers.Get(key)); } } result.responseCode = (int)(response as HttpWebResponse).StatusCode; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { result.body = reader.ReadToEnd(); } } catch (Exception e) { result.responsMessage = e.Message; Log(Severity.Error, String.Format("{0} - {1}", e.GetType().Name, e.Message)); } return(result); }
/// <summary> /// Query if this object issue request 2. /// </summary> /// /// <param name="path"> Full pathname of the file. </param> /// <param name="method"> The method. </param> /// <param name="headers"> The headers. </param> /// <param name="body"> The body. </param> /// <param name="port"> The port. </param> /// /// <returns> /// true if it succeeds, false if it fails. /// </returns> private RequestResponse IssueRequest(string path, string method, Dictionary<string, string> headers, string body, Int32 port) { IWebServiceRequest ds = getInterface<IWebServiceRequest>(); RequestResponse response = new RequestResponse(); if (ds != null) { ds.WebServiceRequest( new RequestSetttings { method = method, uri = new Uri(string.Format("http{0}://{1}{2}{3}/{4}", settings.Secure ? "s" : String.Empty, settings.Host, port == 80 ? String.Empty : String.Format(":{0}", port), String.IsNullOrEmpty(settings.BasePath.TrimEnd('/')) ? "" : settings.BasePath.TrimEnd('/'), path.TrimStart('/') )), requestHeaders = headers, //! allowedResponsCodes, // TODO default is ok body = body, // or method.Equals("GET")?string.Empty:body }, out response); } return response; }
public void WebServiceRequestAux(RequestSetttings requestSettings, bool async, Action <RequestResponse> callback) { RequestResponse result = new RequestResponse(requestSettings); try { UnityWebRequest request = null; switch (requestSettings.method.ToUpper()) { case "GET": request = UnityWebRequest.Get(requestSettings.uri); break; case "POST": request = UnityWebRequest.Post(requestSettings.uri, ""); break; case "PUT": request = UnityWebRequest.Put(requestSettings.uri, ""); break; case "DELETE": request = UnityWebRequest.Delete(requestSettings.uri); break; } if (!string.IsNullOrEmpty(requestSettings.body)) { byte[] bytes = Encoding.UTF8.GetBytes(requestSettings.body); UploadHandlerRaw uH = new UploadHandlerRaw(bytes); if (requestSettings.requestHeaders.ContainsKey("Content-Type")) { uH.contentType = requestSettings.requestHeaders["Content-Type"]; } request.uploadHandler = uH; } foreach (var header in requestSettings.requestHeaders) { request.SetRequestHeader(header.Key, header.Value); } if (async || Application.platform == RuntimePlatform.WebGLPlayer) { Observable.FromCoroutine(() => DoRequest(request, operation => { var uwr = operation.webRequest; CopyResponse(result, uwr); callback(result); })).Subscribe(); } else { request.SendWebRequest(); while (!request.isDone) { } CopyResponse(result, request); callback(result); } } catch (Exception e) { result.responsMessage = e.Message; Log(Severity.Error, String.Format("{0} - {1}", e.GetType().Name, e.Message)); } }
/// <summary> /// Web service request. /// </summary> /// /// <param name="requestSettings"> Options for controlling the operation. </param> /// /// <returns> /// A RequestResponse. /// </returns> private RequestResponse WebServiceRequest(RequestSetttings requestSettings) #endif { RequestResponse result = new RequestResponse(requestSettings); try { //! Might throw a silent System.IOException on .NET 3.5 (sync). HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestSettings.uri); request.Method = requestSettings.method; // TODO Cookies // Both Accept and Content-Type are not allowed as Headers in a HttpWebRequest. // They need to be assigned to a matching property. if (requestSettings.requestHeaders.ContainsKey("Accept")) { request.Accept = requestSettings.requestHeaders["Accept"]; } if (!String.IsNullOrEmpty(requestSettings.body)) { byte[] data = Encoding.UTF8.GetBytes(requestSettings.body); if (requestSettings.requestHeaders.ContainsKey("Content-Type")) { request.ContentType = requestSettings.requestHeaders["Content-Type"]; } foreach (KeyValuePair<string, string> kvp in requestSettings.requestHeaders) { if (kvp.Key.Equals("Accept") || kvp.Key.Equals("Content-Type")) { continue; } request.Headers.Add(kvp.Key, kvp.Value); } request.ContentLength = data.Length; // See https://msdn.microsoft.com/en-us/library/system.net.servicepoint.expect100continue(v=vs.110).aspx // A2 currently does not support this 100-Continue response for POST requets. request.ServicePoint.Expect100Continue = false; #if ASYNC Stream stream = await request.GetRequestStreamAsync(); await stream.WriteAsync(data, 0, data.Length); stream.Close(); #else Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); #endif } else { foreach (KeyValuePair<string, string> kvp in requestSettings.requestHeaders) { if (kvp.Key.Equals("Accept") || kvp.Key.Equals("Content-Type")) { continue; } request.Headers.Add(kvp.Key, kvp.Value); } } #if ASYNC WebResponse response = await request.GetResponseAsync(); #else WebResponse response = request.GetResponse(); #endif if (response.Headers.HasKeys()) { foreach (string key in response.Headers.AllKeys) { result.responseHeaders.Add(key, response.Headers.Get(key)); } } result.responseCode = (int)(response as HttpWebResponse).StatusCode; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { #if ASYNC result.body = await reader.ReadToEndAsync(); #else result.body = reader.ReadToEnd(); #endif } } catch (Exception e) { result.responsMessage = e.Message; // Log(Severity.Error, String.Format("{0} - {1}", e.GetType().Name, e.Message)); } return result; }
/// <summary> /// Web service request. /// </summary> /// /// <param name="requestSettings"> Options for controlling the operation. </param> /// <param name="requestResponse"> The request response. </param> public void WebServiceRequest(RequestSetttings requestSettings, out RequestResponse requestResponse) { requestResponse = WebServiceRequest(requestSettings); }
// See http://stackoverflow.com/questions/12224602/a-method-for-making-http-requests-on-unity-ios // for persistence. // See http://18and5.blogspot.com.es/2014/05/mono-unity3d-c-https-httpwebrequest.html #if ASYNC public void WebServiceRequest(RequestSetttings requestSettings, out RequestResponse requestReponse) { // Wrap the actual method in a Task. Neccesary because we cannot: // 1) Make this method async (out is not allowed) // 2) Return a Task<RequestResponse> as it breaks the interface (only void does not break it). // Task<RequestResponse> taskName = Task.Factory.StartNew<RequestResponse>(() => { return WebServiceRequestAsync(requestSettings).Result; }); requestReponse = taskName.Result; }