JD2022-TU1/main/phone_apps/JDCompanionApp/Assets/Scripts/Online/HttpEngine_WebRequest.cs

92 lines
3.2 KiB
C#

using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using LightJSON;
using uPromise;
using UnityEngine;
namespace Online
{
public class HttpEngine_WebRequest: IHttpEngine
{
public Promise<HttpResponse> Execute(HttpRequest request)
{
var deferred = new Deferred<HttpResponse>();
var postData = (request.PostData != null) ? Encoding.UTF8.GetBytes(JSON.Stringify(request.PostData)) : null;
Debug.Log("[HTTP] Starting " + request.Url);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(request.Url);
foreach (var header in request.Headers)
{
Debug.Log("[HTTP] " + header.Key + ": " + header.Value);
httpWebRequest.Headers.Add(header.Key + ": " + header.Value);
}
if (request.PostData != null)
{
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = postData.Length;
httpWebRequest.ContentType = "application/json";
var writeStream = httpWebRequest.GetRequestStream();
writeStream.Write(postData, 0, postData.Length);
writeStream.Close();
}
// should not be required, but some requests seem to incorrectly reuse the same socket
httpWebRequest.KeepAlive = false;
IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);
GlobalMonoBehaviour.Instance.StartCoroutine(WaitForRequest(deferred, httpWebRequest, asyncResult));
return deferred.Promise;
}
private IEnumerator WaitForRequest(Deferred<HttpResponse> deferred, HttpWebRequest httpWebRequest, IAsyncResult asyncResult)
{
while (!asyncResult.IsCompleted)
yield return null;
HttpResponse response = new HttpResponse();
HttpWebResponse httpWebResponse = null;
try
{
httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult);
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
// protocol error; consider the HTTP call a success (i.e forward 4XX and 5XX status codes to services)
httpWebResponse = (HttpWebResponse)e.Response;
}
else
{
// other issue (timeout, malformed server response, IO error, ...)
deferred.Reject();
yield break;
}
}
response.StatusCode = (int)httpWebResponse.StatusCode;
foreach (string name in httpWebResponse.Headers.Keys)
response.Headers[name] = httpWebResponse.Headers.Get(name);
var responseReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
response.Body = JSON.Parse(responseReader.ReadToEnd());
httpWebResponse.Close();
yield return new WaitForSeconds(1.0f);
deferred.Resolve(response);
}
}
}