internal static IEnumerator Request(MonoBehaviour caller, EngageRequest request, EngageResponse response) { string requestJSON = request.ToJSON(); string url = DDNA.Instance.ResolveEngageURL(requestJSON); HttpRequest httpRequest = new HttpRequest(url); httpRequest.HTTPMethod = HttpRequest.HTTPMethodType.POST; httpRequest.HTTPBody = requestJSON; httpRequest.TimeoutSeconds = DDNA.Instance.Settings.HttpRequestEngageTimeoutSeconds; httpRequest.setHeader("Content-Type", "application/json"); System.Action<int, string, string> httpHandler = (statusCode, data, error) => { string engagementKey = "DDSDK_ENGAGEMENT_" + request.DecisionPoint + "_" + request.Flavour; if (error == null && statusCode >= 200 && statusCode < 300) { try { PlayerPrefs.SetString(engagementKey, data); } catch (Exception exception) { Logger.LogWarning("Unable to cache engagement: "+exception.Message); } } else { Logger.LogDebug("Engagement failed with "+statusCode+" "+error); if (PlayerPrefs.HasKey(engagementKey)) { Logger.LogDebug("Using cached response"); data = "{\"isCachedResponse\":true," + PlayerPrefs.GetString(engagementKey).Substring(1); } else { data = "{}"; } } response(data, statusCode, error); }; yield return caller.StartCoroutine(Network.SendRequest(httpRequest, httpHandler)); }
internal static IEnumerator SendRequest(HttpRequest request, Action<int /*statusCode*/, string /*data*/, string /*error*/> completionHandler) { WWW www; if (request.HTTPMethod == HttpRequest.HTTPMethodType.POST) { Dictionary<string, string> headers = new Dictionary<string, string>(); WWWForm form = new WWWForm(); foreach (var entry in Utils.HashtableToDictionary<string, string>(form.headers)) { headers[entry.Key] = entry.Value; } foreach (var entry in request.getHeaders()) { headers[entry.Key] = entry.Value; } byte[] bytes = Encoding.UTF8.GetBytes(request.HTTPBody); www = new WWW(request.URL, bytes, headers); } else { www = new WWW(request.URL); } float timer = 0; bool timedout = false; while (!www.isDone) { if (timer > request.TimeoutSeconds) { timedout = true; break; } timer += Time.deltaTime; yield return null; } int statusCode = 1001; string data = null; string error = null; if (timedout) { www.Dispose(); error = "connect() timed out"; } else { statusCode = ReadStatusCode(www); data = www.text; error = www.error; } if (completionHandler != null) { completionHandler(statusCode, data, error); } }