WebRequest has no GetResponse method - Windows Phone 8

后端 未结 1 1924
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 13:30

I want to send a post request to an API with some parameters they ask for... I ended up just creating a string, it\'s ugly but I do not know a way of making it work differen

相关标签:
1条回答
  • 2020-12-22 13:56

    The .NET compilation for Windows Phone contains an implementation of the WebRequest class which does not have synchronous methods for obtaining request stream and response, as these would block execution on the UI thread until the operations completed. You can use the existing Begin/End methods directly with callback delegates, or you can wrap those calls in async extensions that will give you the kind of readability and functionality you're used to (more or less). My preferred method is defining extensions, so I will demonstrate this method, but it has no performance advantage over the callback pattern. It does have the up-side of being easily portable any time you need to make use of a WebRequest.

    Async/Await Pattern

    Define custom extensions for the WebRequest class:

    public static class Extensions
    {
        public static System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync(this System.Net.WebRequest wr)
        {
            if (wr.ContentLength < 0)
            {
                throw new InvalidOperationException("The ContentLength property of the WebRequest must first be set to the length of the content to be written to the stream.");
            }
    
            return Task<System.IO.Stream>.Factory.FromAsync(wr.BeginGetRequestStream, wr.EndGetRequestStream, null);
        }
    
        public static System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync(this System.Net.WebRequest wr)
        {
            return Task<System.Net.WebResponse>.Factory.FromAsync(wr.BeginGetResponse, wr.EndGetResponse, null);
        }
    }
    

    Use the new extensions (be sure to import the namespace where your static Extensions class was defined):

    public async System.Threading.Tasks.Task<bool> AuthenticateAsync()
    {
        byte[] dataStream = System.Text.Encoding.UTF8.GetBytes("...");
        System.Net.WebRequest webRequest = System.Net.WebRequest.Create("...");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json";
        webRequest.ContentLength = dataStream.Length;
        Stream newStream = await webRequest.GetRequestStreamAsync();
        // Send the data.
        newStream.Write(dataStream, 0, dataStream.Length);
        newStream.Close();
        var webResponse = await webRequest.GetResponseAsync();
    
        return true;
    }
    

    Regarding your final note, at the moment I don't see enough information to make sense of what the callback URI is, where it's defined, and how it affects what you're doing.

    0 讨论(0)
提交回复
热议问题