private static async Task Run(string url, OAuthRequestMethod method, Dictionary <string, string> parameters, Action <OAuthRequestResult> onSuccess, Action <OAuthRequestResult> onError, SynchronizationContext context) { var result = new OAuthRequestResult(); switch (method) { case OAuthRequestMethod.GET: { var response = await httpClient.GetAsync(url); var text = await response.Content.ReadAsStringAsync(); result.Text = text; result.IsSuccess = response.IsSuccessStatusCode; result.StatusCode = (long)response.StatusCode; } break; case OAuthRequestMethod.POST: { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); var content = string.Join("&", parameters.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}")); request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.SendAsync(request); var text = await response.Content.ReadAsStringAsync(); result.Text = text; result.IsSuccess = response.IsSuccessStatusCode; result.StatusCode = (long)response.StatusCode; } break; } context.Post(_ => { if (!result.IsSuccess) { onError(result); return; } onSuccess(result); }, null); }
public override void Request(Dictionary <string, string> parameters, Action <OAuthRequestResult> onSuccess, Action <OAuthRequestResult> onError) { if (m_request != null && !m_request.isDone) { Debug.LogError("未完了のリクエストがあります!"); return; } var parsedUrl = ParseURL(parameters); switch (Method) { case OAuthRequestMethod.GET: m_request = UnityWebRequest.Get(parsedUrl); break; case OAuthRequestMethod.POST: var form = new WWWForm(); foreach (var param in parameters) { form.AddField(param.Key, param.Value); } m_request = UnityWebRequest.Post(parsedUrl, form); break; } var operation = m_request.SendWebRequest(); operation.completed += (op) => { var result = new OAuthRequestResult(); result.Text = m_request.downloadHandler.text; result.IsSuccess = !m_request.isHttpError && !m_request.isNetworkError; result.StatusCode = m_request.responseCode; m_request = null; if (!result.IsSuccess) { onError(result); return; } onSuccess(result); }; }