Question Write webrequest async way

DARK__FOXX

Member
Joined
Sep 2, 2020
Messages
16
Programming Experience
Beginner
Hi,

I found this function to create a request POST that visualize json data in an ASP:NET project, I would like to find a way to make async, but i don't know how to do.

VB.NET:
Private Function SendRequestPOST(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String, token As String) As String
    Dim response As String
    Dim request As HttpWebRequest

    request = WebRequest.Create(uri)
    request.PreAuthenticate = True
    request.Headers.Add("Authorization", "Bearer " + token)
    request.Accept = contentType
    request.Method = method

    Using requestStream = request.GetRequestStream
        requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
        requestStream.Close()

        Using responseStream = request.GetResponse.GetResponseStream
            Using reader As New StreamReader(responseStream)
                response = reader.ReadToEnd()
            End Using
        End Using
    End Using

    Return response
End Function

I know that i need to use these method:
BeginGetRequestStream / EndGetRequestStream
BeginGetResponse / EndGetResponse
but I don't know where to use and If i need to use Task
 
Last edited by a moderator:
The inline code tag is for inline code, like if you want to say that you used a TextBox in your app. If you're posting a code snippet, please use the correct code tag. I have fixed your post for readability.
 
Using those Begin/End methods is a bit of an old school way to write asynchronous code. These days, you should use the Tasks Parallel Library and Async/Await if possible. You can make your own method async and then call all the async versions of the synchronous methods you're already calling to change the code very little:
VB.NET:
Private Async Function SendRequestPostAsync(uri As Uri,
                                            jsonDataBytes As Byte(),
                                            contentType As String,
                                            method As String,
                                            token As String) As Task(Of String)
    Dim request = DirectCast(WebRequest.Create(uri), HttpWebRequest)

    request.PreAuthenticate = True
    request.Headers.Add("Authorization", "Bearer " + token)
    request.Accept = contentType
    request.Method = method

    Dim response As String

    Using requestStream = Await request.GetRequestStreamAsync()
        Await requestStream.WriteAsync(jsonDataBytes, 0, jsonDataBytes.Length)
        requestStream.Close()

        Using responseStream = (Await request.GetResponseAsync()).GetResponseStream(),
              reader As New StreamReader(responseStream)
            response = Await reader.ReadToEndAsync()
        End Using
    End Using

    Return response
End Function
I took the liberty of cleaning up a few other bits and pieces there.
 
Using those Begin/End methods is a bit of an old school way to write asynchronous code. These days, you should use the Tasks Parallel Library and Async/Await if possible. You can make your own method async and then call all the async versions of the synchronous methods you're already calling to change the code very little:
VB.NET:
Private Async Function SendRequestPostAsync(uri As Uri,
                                            jsonDataBytes As Byte(),
                                            contentType As String,
                                            method As String,
                                            token As String) As Task(Of String)
    Dim request = DirectCast(WebRequest.Create(uri), HttpWebRequest)

    request.PreAuthenticate = True
    request.Headers.Add("Authorization", "Bearer " + token)
    request.Accept = contentType
    request.Method = method

    Dim response As String

    Using requestStream = Await request.GetRequestStreamAsync()
        Await requestStream.WriteAsync(jsonDataBytes, 0, jsonDataBytes.Length)
        requestStream.Close()

        Using responseStream = (Await request.GetResponseAsync()).GetResponseStream(),
              reader As New StreamReader(responseStream)
            response = Await reader.ReadToEndAsync()
        End Using
    End Using

    Return response
End Function
I took the liberty of cleaning up a few other bits and pieces there.
Thanks!
And If I need to test the result, or that I return the json on the page what can I do? I'd like to view it inside a div
 
Thanks!
And If I need to test the result, or that I return the json on the page what can I do? I'd like to view it inside a div
To get the result of an asynchronous method, you would await it in another async method, just as I have awaited multiple async methods in this code, or you can do this:
VB.NET:
var result = SomeAsyncMethod.Result;
If SomeAsyncMethod has a return type of Task<string> then that Result will be type string. Unlike awaiting, that code will block. Once you have the string, you can do whatever you like with it, just as you can with any other string.
 
Could you give me an example to better understand? I tried to run it in fact the page keeps turning without showing me the json

I tried this:

Json:
 Dim ListProducts As New ListProducts
        Dim JsonListProducts As String = JsonConvert.SerializeObject(ListProducts, Formatting.Indented)
        Dim data2 = Encoding.UTF8.GetBytes(JsonListProducts)
        'Dim uri  As New Uri("http://xxxxxxxxxxxxxxx/") 'my url
        Dim result_POST_Async As String = SendRequestPostAsync(uri, data2, "application/json", "POST", TokenGiven).Result
        div.InnerHtml = result_POST_Async
 
Last edited:
Back
Top