public static async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey, Dictionary <string, string> extraHeaders, PlayFabApiSettings apiSettings = null) { var fullPath = apiSettings == null?PlayFabSettings.GetFullUrl(urlPath, PlayFabSettings.RequestGetParams) : apiSettings.GetFullUrl(urlPath, PlayFabSettings.RequestGetParams); var titleId = apiSettings?.TitleId == null ? PlayFabSettings.TitleId : apiSettings.TitleId; if (titleId == null) { throw new PlayFabException(PlayFabExceptionCode.TitleNotSet, "You must set your titleId before making an api call"); } var transport = PluginManager.GetPlugin <ITransportPlugin>(PluginContract.PlayFab_Transport); var headers = new Dictionary <string, string>(); if (authType != null && authKey != null) { headers[authType] = authKey; } if (extraHeaders != null) { foreach (var extraHeader in extraHeaders) { headers.Add(extraHeader.Key, extraHeader.Value); } } return(await transport.DoPost(fullPath, request, headers)); }
/// <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); } }
protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, bool allowQueueing = false, PlayFabAuthenticationContext authenticationContext = null, PlayFabApiSettings apiSettings = null) where TResult : PlayFabResultCommon { var fullUrl = apiSettings == null?PlayFabSettings.GetFullUrl(apiEndpoint, PlayFabSettings.RequestGetParams) : apiSettings.GetFullUrl(apiEndpoint, apiSettings.RequestGetParams); _MakeApiCall(apiEndpoint, fullUrl, request, authType, resultCallback, errorCallback, customData, extraHeaders, allowQueueing, authenticationContext, apiSettings); }
/// <summary> /// Internal method for Make API Calls /// </summary> protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, bool allowQueueing = false) where TResult : PlayFabResultCommon { InitializeHttp(); SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre); var reqContainer = new CallRequestContainer { ApiEndpoint = apiEndpoint, FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint), CustomData = customData, Payload = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request, PlayFabUtil.ApiSerializerStrategy)), AuthKey = authType, ApiRequest = request, ErrorCallback = errorCallback, }; #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.StartTimeUtc = DateTime.UtcNow; reqContainer.Timing.ApiEndpoint = apiEndpoint; #endif // These closures preserve the TResult generic information in a way that's safe for all the devices reqContainer.DeserializeResultJson = () => { reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse, PlayFabUtil.ApiSerializerStrategy); }; reqContainer.InvokeSuccessCallback = () => { if (resultCallback != null) { resultCallback((TResult)reqContainer.ApiResult); } }; if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted) { for (var i = _apiCallQueue.Count - 1; i >= 0; i--) { if (_apiCallQueue[i].ApiEndpoint == apiEndpoint) { _apiCallQueue.RemoveAt(i); } } _apiCallQueue.Add(reqContainer); } else { _internalHttp.MakeApiCall(reqContainer); } }
// 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; } }
/// <summary> /// Internal method for Make API Calls /// </summary> protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, bool allowQueueing = false) where TResult : PlayFabResultCommon { InitializeHttp(); SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre); var reqContainer = new CallRequestContainer { ApiEndpoint = apiEndpoint, FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint), CustomData = customData, Payload = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request)), ApiRequest = request, ErrorCallback = errorCallback, RequestHeaders = extraHeaders ?? new Dictionary <string, string>() // Use any headers provided by the customer }; // Append any additional headers foreach (var pair in GlobalHeaderInjection) { if (!reqContainer.RequestHeaders.ContainsKey(pair.Key)) { reqContainer.RequestHeaders[pair.Key] = pair.Value; } } #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.StartTimeUtc = DateTime.UtcNow; reqContainer.Timing.ApiEndpoint = apiEndpoint; #endif // Add PlayFab Headers reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true"; // Makes processing PlayFab errors a little easier reqContainer.RequestHeaders["X-PlayFabSDK"] = PlayFabSettings.VersionString; // Tell PlayFab which SDK this is switch (authType) { #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API case AuthType.DevSecretKey: reqContainer.RequestHeaders["X-SecretKey"] = PlayFabSettings.DeveloperSecretKey; break; #endif case AuthType.LoginSession: reqContainer.RequestHeaders["X-Authorization"] = _internalHttp.AuthKey; break; case AuthType.EntityToken: reqContainer.RequestHeaders["X-EntityToken"] = _internalHttp.EntityToken; break; } // These closures preserve the TResult generic information in a way that's safe for all the devices reqContainer.DeserializeResultJson = () => { reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse); }; reqContainer.InvokeSuccessCallback = () => { if (resultCallback != null) { resultCallback((TResult)reqContainer.ApiResult); } }; if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted) { for (var i = _apiCallQueue.Count - 1; i >= 0; i--) { if (_apiCallQueue[i].ApiEndpoint == apiEndpoint) { _apiCallQueue.RemoveAt(i); } } _apiCallQueue.Add(reqContainer); } else { _internalHttp.MakeApiCall(reqContainer); } }
public async Task <object> DoPost(string urlPath, object request, Dictionary <string, string> extraHeaders) { var serializer = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer); var fullUrl = PlayFabSettings.GetFullUrl(urlPath, PlayFabSettings.RequestGetParams); string bodyString; if (request == null) { bodyString = "{}"; } else { bodyString = serializer.SerializeObject(request); } var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(fullUrl)); requestMessage.Content = new HttpStringContent(bodyString, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"); requestMessage.Headers.Add(new KeyValuePair <string, string>("X-PlayFabSDK", PlayFabSettings.SdkVersionString)); if (extraHeaders != null) { foreach (var headerPair in extraHeaders) { requestMessage.Headers.Add(headerPair); } } HttpResponseMessage httpResponse; string httpResponseString; try { httpResponse = await _client.SendRequestAsync(requestMessage); httpResponseString = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception e) { return(new PlayFabError { Error = PlayFabErrorCode.ConnectionError, ErrorMessage = e.Message }); } if (!httpResponse.IsSuccessStatusCode) { var error = new PlayFabError(); if (string.IsNullOrEmpty(httpResponseString)) { error.HttpCode = (int)httpResponse.StatusCode; error.HttpStatus = httpResponse.StatusCode.ToString(); return(error); } PlayFabJsonError errorResult; try { errorResult = serializer.DeserializeObject <PlayFabJsonError>(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)) { return(new PlayFabError { Error = PlayFabErrorCode.Unknown, ErrorMessage = "Internal server error" }); } return(httpResponseString); }
public async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey, Dictionary <string, string> extraHeaders) { var fullUrl = PlayFabSettings.GetFullUrl(urlPath); string bodyString; if (request == null) { bodyString = "{}"; } else { bodyString = JsonWrapper.SerializeObject(request); } var client = new HttpClient(); HttpResponseMessage httpResponse; string httpResponseString; using (var 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", PlayFabSettings.SdkVersionString); if (extraHeaders != null) { foreach (var headerPair in extraHeaders) { postBody.Headers.Add(headerPair.Key, headerPair.Value); } } try { httpResponse = await client.PostAsync(fullUrl, postBody); httpResponseString = await httpResponse.Content.ReadAsStringAsync(); } catch (HttpRequestException e) { return(new PlayFabError { Error = PlayFabErrorCode.ConnectionError, ErrorMessage = e.InnerException.Message }); } catch (Exception e) { return(new PlayFabError { Error = PlayFabErrorCode.ConnectionError, ErrorMessage = e.Message }); } } if (!httpResponse.IsSuccessStatusCode) { var 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; try { errorResult = JsonWrapper.DeserializeObject <PlayFabJsonError>(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)) { return(new PlayFabError { Error = PlayFabErrorCode.Unknown, ErrorMessage = "Internal server error" }); } return(httpResponseString); }
protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, bool allowQueueing = false) where TResult : PlayFabResultCommon { PlayFabHttp.InitializeHttp(); PlayFabHttp.SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre); CallRequestContainer reqContainer = new CallRequestContainer { ApiEndpoint = apiEndpoint, FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint), CustomData = customData, Payload = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request)), ApiRequest = request, ErrorCallback = errorCallback, RequestHeaders = (extraHeaders ?? new Dictionary <string, string>()) }; foreach (KeyValuePair <string, string> keyValuePair in PlayFabHttp.GlobalHeaderInjection) { if (!reqContainer.RequestHeaders.ContainsKey(keyValuePair.Key)) { reqContainer.RequestHeaders[keyValuePair.Key] = keyValuePair.Value; } } reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true"; reqContainer.RequestHeaders["X-PlayFabSDK"] = "UnitySDK-2.39.180409"; if (authType != AuthType.LoginSession) { if (authType == AuthType.EntityToken) { reqContainer.RequestHeaders["X-EntityToken"] = PlayFabHttp._internalHttp.EntityToken; } } else { reqContainer.RequestHeaders["X-Authorization"] = PlayFabHttp._internalHttp.AuthKey; } reqContainer.DeserializeResultJson = delegate() { reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse); }; reqContainer.InvokeSuccessCallback = delegate() { if (resultCallback != null) { resultCallback((TResult)((object)reqContainer.ApiResult)); } }; if (allowQueueing && PlayFabHttp._apiCallQueue != null && !PlayFabHttp._internalHttp.SessionStarted) { for (int i = PlayFabHttp._apiCallQueue.Count - 1; i >= 0; i--) { if (PlayFabHttp._apiCallQueue[i].ApiEndpoint == apiEndpoint) { PlayFabHttp._apiCallQueue.RemoveAt(i); } } PlayFabHttp._apiCallQueue.Add(reqContainer); } else { PlayFabHttp._internalHttp.MakeApiCall(reqContainer); } }
public async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey) { var fullUrl = PlayFabSettings.GetFullUrl(urlPath); string bodyString; if (request == null) { bodyString = "{}"; } else { bodyString = JsonWrapper.SerializeObject(request); } var httpClient = new HttpClient(); var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(fullUrl)); requestMessage.Content = new HttpStringContent(bodyString, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"); if (authType != null) { requestMessage.Headers.Add(new KeyValuePair <string, string>(authType, authKey)); } requestMessage.Headers.Add(new KeyValuePair <string, string>("X-PlayFabSDK", PlayFabSettings.SdkVersionString)); HttpResponseMessage httpResponse; string httpResponseString; try { httpResponse = await httpClient.SendRequestAsync(requestMessage); httpResponseString = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception e) { return(new PlayFabError { Error = PlayFabErrorCode.ConnectionError, ErrorMessage = e.Message }); } if (!httpResponse.IsSuccessStatusCode) { var error = new PlayFabError(); if (string.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == HttpStatusCode.NotFound) { error.HttpCode = (int)httpResponse.StatusCode; error.HttpStatus = httpResponse.StatusCode.ToString(); return(error); } PlayFabJsonError errorResult; try { errorResult = JsonWrapper.DeserializeObject <PlayFabJsonError>(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)) { return(new PlayFabError { Error = PlayFabErrorCode.Unknown, ErrorMessage = "Internal server error" }); } return(httpResponseString); }
public static async Task <object> DoPost(string urlPath, object request, string authType, string authKey) { string fullUrl = PlayFabSettings.GetFullUrl(urlPath); 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", PlayFabSettings.SdkVersionString); HttpResponseMessage httpResponse = null; String httpResponseString = null; try { httpResponse = await client.PostAsync(fullUrl, 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); }