简体   繁体   中英

Converting HttpWebRequest to UnityWebRequest

How do you write the below code using UnityWebRequest Put message instead of HttpWebRequest from System.net.

I need to make a PUT call in WebGL, since HttpWebRequest does not work on that platform. I tried to somehow convert it but that did not work for me.

Instead of these two methods, I need one UnityWebRequest Put method.

 public static void InvokeHttpRequest(Uri endpointUri, string httpMethod,
            IDictionary<string, string> headers, string requestBody)
{
    try
    {
        var request = ConstructWebRequest(endpointUri, httpMethod, headers);

        if (!string.IsNullOrEmpty(requestBody))
        {
            var buffer = new byte[8192]; // arbitrary buffer size                        
            var requestStream = request.GetRequestStream();

            using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
            {
                int bytesRead;

                while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
            }
        }

        CheckResponse(request);
    }
    catch (WebException ex)
    {
        using (var response = ex.Response as HttpWebResponse)
        {
            if (response != null)
            {
                var errorMsg = ReadResponseBody(response);
                Debug.LogError(
                    $"\n-- HTTP call failed with exception '{errorMsg}'," +
                    $" status code '{response.StatusCode}'");
            }
        }
    }
}

    public static HttpWebRequest ConstructWebRequest(Uri endpointUri, string httpMethod,
    IDictionary<string, string> headers)
{
    var request = (HttpWebRequest) WebRequest.Create(endpointUri);

    request.Method = httpMethod;

    foreach (var header in headers.Keys)
    {
        // not all headers can be set via the dictionary
        if (header.Equals("host", StringComparison.OrdinalIgnoreCase))
        {
            request.Host = headers[header];
        }
        else if (header.Equals("content-length", StringComparison.OrdinalIgnoreCase))
        {
            request.ContentLength = long.Parse(headers[header]);
        }
        else if (header.Equals("content-type", StringComparison.OrdinalIgnoreCase))
        {
            request.ContentType = headers[header];
        }
        else
        {
            request.Headers.Add(header, headers[header]);
        }
    }

    return request;
}
 private IEnumerator PostRequest(Uri uri, IDictionary<string, string> formHeaders, string contentBody)
{
    var uwr = new UnityWebRequest(uri, "PUT");
    var contentBytes = new UTF8Encoding().GetBytes(contentBody);
    uwr.uploadHandler = new UploadHandlerRaw(contentBytes);
    uwr.downloadHandler = new DownloadHandlerBuffer();

    foreach (var header in formHeaders.Keys)
    {
        // not all headers can be set via the dictionary
        if (header.Equals("host", StringComparison.OrdinalIgnoreCase))
        {
            uwr.SetRequestHeader("host", formHeaders[header]);
        }
        else if (header.Equals("content-length", StringComparison.OrdinalIgnoreCase))
        {
            uwr.SetRequestHeader("content-length", formHeaders[header]);
        }
        else if (header.Equals("content-type", StringComparison.OrdinalIgnoreCase))
        {
            uwr.SetRequestHeader("content-type", formHeaders[header]);
        }
        else
        {
            uwr.SetRequestHeader(header, formHeaders[header]);
        }
    }

    //Send the request then wait here until it returns
    yield return uwr.SendWebRequest();

    if (uwr.isNetworkError)
    {
        Debug.Log("Error While Sending: " + uwr.error);
    }
    else
    {
        Debug.Log("Received: " + uwr.downloadHandler.text);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM