//This is the old Unity WWW class call. private IEnumerator MakeRequestViaUnity(string url, string data, string authType, string authKey, Action <string, PlayFabError> 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)) { var error = GeneratePfError(HttpStatusCode.ServiceUnavailable, PlayFabErrorCode.ServiceUnavailable, www.error, null); callback(null, error); } else { string response = www.text; callback(response, null); } }
/// <summary> /// Sends a POST HTTP request /// </summary> public static void Post(string urlPath, string data, string authType, string authKey, Action <CallRequestContainer> callback, object request, object customData, bool isBlocking = false) { var requestContainer = new CallRequestContainer { RequestType = PlayFabSettings.RequestType, CallId = callIdGen++, AuthKey = authKey, AuthType = authType, Callback = callback, Data = data, Url = urlPath, Request = request, CustomData = customData }; if (!isBlocking) { #if PLAYFAB_IOS_PLUGIN PlayFabiOSPlugin.Post(PlayFabSettings.GetFullUrl(urlPath), PlayFabVersion.getVersionString(), requestContainer, PlayFabSettings.InvokeRequest); #elif UNITY_WP8 instance.StartCoroutine(instance.MakeRequestViaUnity(requestContainer)); #else if (PlayFabSettings.RequestType == WebRequestType.HttpWebRequest) { lock (ActiveRequests) ActiveRequests.Insert(0, requestContainer); // Parsing on this container is done backwards, so insert at 0 to make calls process in roughly queue order (but still not actually guaranteed) PlayFabSettings.InvokeRequest(urlPath, requestContainer.CallId, request, customData); _ActivateWorkerThread(); } else { instance.StartCoroutine(instance.MakeRequestViaUnity(requestContainer)); } #endif } else { StartHttpWebRequest(requestContainer); ProcessHttpWebResult(requestContainer, true); callback(requestContainer); } }
/// <summary> /// Sends a POST HTTP request /// </summary> public static void Post(string url, string data, string authType, string authKey, Action <string, PlayFabError> callback) { #if PLAYFAB_IOS_PLUGIN PlayFabiOSPlugin.Post(url, data, authType, authKey, PlayFabVersion.getVersionString(), callback); #else PlayFabHTTP.instance.InstPost(url, data, authType, authKey, callback); #endif }
private void MakeRequestViaWebRequestSyncronous(string url, string data, string authType, string authKey, Action <string, PlayFabError> callback) { HttpWebResponse response = null; try { byte[] payload = System.Text.Encoding.UTF8.GetBytes(data); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //Prevents hitting a proxy is no proxy is available. request.Proxy = null; //TODO: Add support for proxy's. request.Headers.Add("X-ReportErrorAsSuccess", "true"); request.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); if (authType != null) { request.Headers.Add(authType, authKey); } request.ContentType = "application/json"; request.Method = "POST"; request.KeepAlive = PlayFabSettings.RequestKeepAlive; request.Timeout = PlayFabSettings.RequestTimeout; //Get Request Stream and send data in the body. using (var stream = request.GetRequestStream()) { stream.Write(payload, 0, payload.Length); } response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { using (var stream = new System.IO.StreamReader(response.GetResponseStream())) { var result = stream.ReadToEnd(); callback(result, null); } } else { HttpStatusCode httpCode = response == null ? HttpStatusCode.ServiceUnavailable : response.StatusCode; var error = GeneratePfError(httpCode, PlayFabErrorCode.ServiceUnavailable, "Failed to connect to PlayFab server", null); callback(null, error); } } catch (Exception e) { Debug.LogException(e); HttpStatusCode httpCode = response == null ? HttpStatusCode.ServiceUnavailable : response.StatusCode; var error = GeneratePfError(httpCode, PlayFabErrorCode.ServiceUnavailable, e.ToString(), null); //Lock for protection of simultaneous API calls. callback(null, error); } pendingMessages -= 1; }
private void MakeRequestViaWebRequestSyncronous(string url, string data, string authType, string authKey, Action <string, string> callback) { try { byte[] payload = System.Text.Encoding.UTF8.GetBytes(data); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //Prevents hitting a proxy is no proxy is available. request.Proxy = null; //TODO: Add support for proxy's. request.Headers.Add("X-ReportErrorAsSuccess", "true"); request.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); if (authType != null) { request.Headers.Add(authType, authKey); } request.ContentType = "application/json"; request.Method = "POST"; request.KeepAlive = PlayFabSettings.RequestKeepAlive; request.Timeout = PlayFabSettings.RequestTimeout; //Get Request Stream and send data in the body. using (var stream = request.GetRequestStream()) { stream.Write(payload, 0, payload.Length); } //Debug.LogFormat("Response Code: {0}", response.StatusCode); var response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { using (var stream = new System.IO.StreamReader(response.GetResponseStream())) { var result = stream.ReadToEnd(); callback(result, null); } } else { var error = GetResonseCodeResult(response.StatusCode); var errorString = GenerateJsonError((int)response.StatusCode, error, 1123, error, error); callback(errorString, null); } } catch (Exception e) { Debug.Log(e.Message); Debug.Log(e.StackTrace); var errorString = GenerateJsonError(500, e.Message, 1123, e.Message, e.Message); //Lock for protection of simuiltanious API calls. callback(errorString, null); } }
/// <summary> /// Sends a POST HTTP request /// </summary> public static void Post(string url, string data, string authType, string authKey, Action <string, PlayFabError> callback, bool IsBlocking) { if (IsBlocking) { PlayFabHTTP.instance.MakeRequestViaWebRequestSyncronous(url, data, authType, authKey, callback); } else { #if PLAYFAB_IOS_PLUGIN PlayFabiOSPlugin.Post(url, data, authType, authKey, PlayFabVersion.getVersionString(), callback); #else PlayFabHTTP.instance.InstPost(url, data, authType, authKey, callback); #endif } }
// This is the old Unity WWW class call. private IEnumerator MakeRequestViaUnity(CallRequestContainer requestContainer) { _pendingWwwMessages += 1; string fullUrl = PlayFabSettings.GetFullUrl(requestContainer.Url); byte[] bData = Encoding.UTF8.GetBytes(requestContainer.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 (requestContainer.AuthType != null) { headers.Add(requestContainer.AuthType, requestContainer.AuthKey); } headers.Add("X-ReportErrorAsSuccess", "true"); headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); WWW www = new WWW(fullUrl, bData, headers); PlayFabSettings.InvokeRequest(requestContainer.Url, requestContainer.CallId, requestContainer.Request, requestContainer.CustomData); yield return(www); requestContainer.ResultStr = null; requestContainer.Error = null; if (!String.IsNullOrEmpty(www.error)) { requestContainer.Error = GeneratePfError(HttpStatusCode.ServiceUnavailable, PlayFabErrorCode.ServiceUnavailable, www.error); } else { requestContainer.ResultStr = www.text; } requestContainer.InvokeCallback(); _pendingWwwMessages -= 1; }
private static void StartHttpWebRequest(CallRequestContainer request) { try { string fullUrl = PlayFabSettings.GetFullUrl(request.Url); var payload = Encoding.UTF8.GetBytes(request.Data); request.HttpRequest = (HttpWebRequest)WebRequest.Create(fullUrl); request.HttpRequest.Proxy = null; // Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's. request.HttpRequest.Headers.Add("X-ReportErrorAsSuccess", "true"); // Without this, we have to catch WebException instead, and manually decode the result request.HttpRequest.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); if (request.AuthType != null) { request.HttpRequest.Headers.Add(request.AuthType, request.AuthKey); } request.HttpRequest.ContentType = "application/json"; request.HttpRequest.Method = "POST"; request.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive; request.HttpRequest.Timeout = PlayFabSettings.RequestTimeout; using (var stream = request.HttpRequest.GetRequestStream()) // Get Request Stream and send data in the body. stream.Write(payload, 0, payload.Length); request.State = CallRequestContainer.RequestState.RequestSent; } catch (WebException e) { Debug.LogException(e); // If it's an unexpected exception, we should log it noisily var errorMessage = ResponseToString(e.Response); if (string.IsNullOrEmpty(errorMessage)) { errorMessage = e.ToString(); } request.Error = GeneratePfError(HttpStatusCode.ServiceUnavailable, PlayFabErrorCode.ServiceUnavailable, errorMessage); request.State = CallRequestContainer.RequestState.Error; } catch (Exception e) { Debug.LogException(e); // If it's an unexpected exception, we should log it noisily request.Error = GeneratePfError(HttpStatusCode.ServiceUnavailable, PlayFabErrorCode.ServiceUnavailable, e.ToString()); request.State = CallRequestContainer.RequestState.Error; } }
internal static async Task <string> DoPost(this PlayFabSettings settings, string apiName, string url, object request, string authType, string authKey) { string bodyString = null; var serializer = JsonSerializer.Create(settings.JsonSettings); if (request == null) { bodyString = "{}"; } else if (request is String) { bodyString = (String)request; } else { StringWriter jsonString = new StringWriter(); using (var writer = new JsonTextWriter(jsonString) { Formatting = settings.JsonFormatting }) { serializer.Serialize(writer, request); bodyString = jsonString.ToString(); } } if (settings.ApiCallback != null) { settings.ApiCallback(PlayFabApiEvent.SendingRequest, settings, apiName, "POST", url, bodyString); } HttpResponseMessage httpResponse = null; String httpResponseString = null; using (HttpClient client = settings.CreateClient()) using (ByteArrayContent postBody = new ByteArrayContent(Encoding.UTF8.GetBytes(bodyString))) { postBody.Headers.Add("Content-Type", "application/json"); if (authType != null) { postBody.Headers.Add(authType, authKey); } postBody.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); httpResponse = await client.PostAsync(url, postBody); httpResponseString = await httpResponse.Content.ReadAsStringAsync(); } if (settings.ApiCallback != null) { settings.ApiCallback(PlayFabApiEvent.ReceivedReply, settings, apiName, "POST", url, httpResponseString); } if (!httpResponse.IsSuccessStatusCode) { if (String.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new PlayFabHttpException(httpResponse.StatusCode, httpResponse.ReasonPhrase); } PlayFabJsonError errorResult = null; errorResult = serializer.Deserialize <PlayFabJsonError>(new JsonTextReader(new StringReader(httpResponseString))); throw new PlayFabException(errorResult); } if (String.IsNullOrEmpty(httpResponseString)) { throw new PlayFabException(PlayFabErrorCode.Unknown, "Internal server error"); } return(httpResponseString); }
public static async Task <object> DoPost(string url, object request, string authType, string authKey) { string bodyString = null; var serializer = JsonSerializer.Create(PlayFabSettings.JsonSettings); if (request == null) { bodyString = "{}"; } else if (request is String) { bodyString = (String)request; } else { StringWriter jsonString = new StringWriter(); var writer = new JsonTextWriter(jsonString) { Formatting = PlayFabSettings.JsonFormatting }; serializer.Serialize(writer, request); bodyString = jsonString.ToString(); } HttpClient client = new HttpClient(); ByteArrayContent postBody = new ByteArrayContent(Encoding.UTF8.GetBytes(bodyString)); postBody.Headers.Add("Content-Type", "application/json"); if (authType != null) { postBody.Headers.Add(authType, authKey); } postBody.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); HttpResponseMessage httpResponse = null; String httpResponseString = null; try { httpResponse = await client.PostAsync(url, postBody); httpResponseString = await httpResponse.Content.ReadAsStringAsync(); } catch (HttpRequestException e) { PlayFabError error = new PlayFabError(); error.Error = PlayFabErrorCode.ConnectionError; error.ErrorMessage = e.InnerException.Message; return(error); } catch (Exception e) { PlayFabError error = new PlayFabError(); error.Error = PlayFabErrorCode.ConnectionError; error.ErrorMessage = e.Message; return(error); } if (!httpResponse.IsSuccessStatusCode) { PlayFabError error = new PlayFabError(); if (String.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == System.Net.HttpStatusCode.NotFound) { error.HttpCode = (int)httpResponse.StatusCode; error.HttpStatus = httpResponse.StatusCode.ToString(); return(error); } PlayFabJsonError errorResult = null; try { errorResult = serializer.Deserialize <PlayFabJsonError>(new JsonTextReader(new StringReader(httpResponseString))); } catch (Exception e) { error.HttpCode = (int)httpResponse.StatusCode; error.HttpStatus = httpResponse.StatusCode.ToString(); error.Error = PlayFabErrorCode.JsonParseError; error.ErrorMessage = e.Message; return(error); } error.HttpCode = errorResult.code; error.HttpStatus = errorResult.status; error.Error = (PlayFabErrorCode)errorResult.errorCode; error.ErrorMessage = errorResult.errorMessage; error.ErrorDetails = errorResult.errorDetails; return(error); } if (String.IsNullOrEmpty(httpResponseString)) { PlayFabError error = new PlayFabError(); error.Error = PlayFabErrorCode.Unknown; error.ErrorMessage = "Internal server error"; return(error); } return(httpResponseString); }
private void MakeRequestViaWebRequest(string url, string data, string authType, string authKey, Action <string, PlayFabError> callback) { byte[] payload = System.Text.Encoding.UTF8.GetBytes(data); //TODO: make closure it's own method. Thread workerThread = new Thread(() => { HttpWebRequest request = null; HttpWebResponse response = null; try { request = (HttpWebRequest)WebRequest.Create(url); //Prevents hitting a proxy is no proxy is available. request.Proxy = null; //TODO: Add support for proxy's. request.Headers.Add("X-ReportErrorAsSuccess", "true"); // Without this, we have to catch WebException instead, and manually decode the result request.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString()); if (authType != null) { request.Headers.Add(authType, authKey); } request.ContentType = "application/json"; request.Method = "POST"; request.KeepAlive = PlayFabSettings.RequestKeepAlive; request.Timeout = PlayFabSettings.RequestTimeout; //Get Request Stream and send data in the body. using (var stream = request.GetRequestStream()) { stream.Write(payload, 0, payload.Length); } response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { using (var stream = new System.IO.StreamReader(response.GetResponseStream())) { var result = stream.ReadToEnd(); //Lock for protection of simultaneous API calls. lock (_RunOnMainThreadQueue) { var cbc = new CallBackContainer() { action = callback, result = result, error = null }; _RunOnMainThreadQueue.Enqueue(cbc); } } } else { var error = GeneratePfError(response.StatusCode, PlayFabErrorCode.ServiceUnavailable, "Failed to connect to PlayFab server", null); //Lock for protection of simultaneous API calls. lock (_RunOnMainThreadQueue) { var cbc = new CallBackContainer() { action = callback, result = null, error = error }; _RunOnMainThreadQueue.Enqueue(cbc); } } } catch (WebException e) { HttpStatusCode httpCode = response == null ? HttpStatusCode.ServiceUnavailable : response.StatusCode; var error = GeneratePfError(httpCode, PlayFabErrorCode.ServiceUnavailable, e.ToString(), null); //Lock for protection of simultaneous API calls. lock (_RunOnMainThreadQueue) { var cbc = new CallBackContainer() { action = callback, result = null, error = error }; _RunOnMainThreadQueue.Enqueue(cbc); } } catch (Exception e) { Debug.LogException(e); // If it's an unexpected exception, we should log it noisily HttpStatusCode httpCode = response == null ? HttpStatusCode.ServiceUnavailable : response.StatusCode; var error = GeneratePfError(httpCode, PlayFabErrorCode.ServiceUnavailable, e.ToString(), null); //Lock for protection of simultaneous API calls. lock (_RunOnMainThreadQueue) { var cbc = new CallBackContainer() { action = callback, result = null, error = error }; _RunOnMainThreadQueue.Enqueue(cbc); } } pendingMessages -= 1; }); workerThread.Start(); }