Home > OS >  VB.net POST method using HTTPclient
VB.net POST method using HTTPclient

Time:08-06

Hello I am trying to access a webform with data. However my code does not have error but its not working. It is supposed to send me a text message using the Web API provided by the telco carrier. Any assistance and advise will be greatly appreciated.

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        Dim client As New HttpClient
        Dim url = $"some url"
        Dim data2 = "{""username"": ""someuname"", ""password"":""somepass"", ""msisdn:""some number"", ""content:""Hello, this is a sample broadcast"", ""shortcode_mask:""somemask""}"
        
        Dim payload = Newtonsoft.Json.JsonConvert.SerializeObject(data2)
        Dim buffer = Encoding.UTF8.GetBytes(payload)
        Dim bytes = New Net.Http.ByteArrayContent(buffer)
        bytes.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue("application/json")
       
        Dim request = client.PostAsync(url, bytes)

    Catch Ex As Exception
        Console.WriteLine()
    End Try

End Sub

End Class

CodePudding user response:

There are a few issues in your code. Let me start with the most important one first:

Catch Ex As Exception
    Console.WriteLine()
End Try

This code means: If an error occurs, throw away all useful information about the error that could help me find the cause, then write an empty line to the console and pretend nothing bad happened.

Don't do that. Remove the whole try-catch block, then re-run your code again. If you get an exception: That's great, because .NET is now telling you what is wrong with your code! If you understand the error message, use it to fix your code. If you don't understand it, feel free to ask the community on StackOverflow.


Second issue: This line

Dim request = client.PostAsync(url, bytes)

starts an asynchronous web request. You don't wait for the result, so you don't know whether it succeeded or not.

You're supposed to Await async methods, but if you aren't familiar with the async/await pattern yet, I won't be able to give you all the necessary background in the single StackOverflow answer. Until you have familiarized youself with async/await, you can synchronously wait for the result by accessing the Result property of the Task that has been returned:

Dim response = client.PostAsync(url, bytes).Result
response.EnsureSuccessStatusCode()

Third issue: You JSON-serialize something which is already JSON. If your data is already JSON, just use it as the payload without calling SerializeObject.

CodePudding user response:

Your data2 is a string. When you use the JSON library to serialize it, it probably isn't in the JSON structure that your URL endpoint expects. Create a Type, fill it with data, and pass that to your JsonCoverter

CodePudding user response:

Thank you Heinzi, here is the final working code based on your concepts:

Public Class Form1


Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim client As New HttpClient
    Dim url = $"some url"
    Dim data2 = "
    {""username"": ""some uname"", ""password"": ""somepass"", ""msisdn"": ""somenumber"", ""content"": ""Hello, this is a sample broadcast"", ""shortcode_mask"" :""somemask""}"

    Dim buffer = Encoding.UTF8.GetBytes(data2)
    Dim bytes = New ByteArrayContent(buffer)
    bytes.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/json")


    Dim request1 = Await client.PostAsync(url, bytes)
    Dim response = client.PostAsync(url, bytes).Result
    response.EnsureSuccessStatusCode()


End Sub

End Class

I can now receive text messages :)

  • Related