I am trying to make a simple Post request to an GraphQL API endpoint and receive a 400 status message in VB.NET, even though with the same GraphQL query in Postman, I receive a 200 message.
I have reviewed all of the Microsoft Product Documentation on VB.NET HttpWebRequest and am still receiving a 400 status message from the endpoint (masked due to client reasons). The error pops up at the request.GetResponse() as the endpoint is having issues accepting the body that I have passed.
I made sure to convert the body of Post method into Bytes & have tried many different methods to convert the JSON to a string first with no such luck. Note there are quoted key value pairs in the json to call to the GraphQL API Endpoint.
Any advice on how I should pass in the GraphQL query in JSON format passed as a string using VB.NET?
My sample VB.NET code snippet (a very, very basic Console App with only main Module) is below for you to see how the code is built to date.
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Module WebRequestHealthCheck
Public Sub Main()
Dim request As HttpWebRequest = HttpWebRequest.Create("https://maskedendpointurl.com")
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = "{\""query\"":\""query healthcheckExampleQuery{healthCheck{ok}}\"",\""variables\"":{}}"
Dim byteData As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentLength = byteData.Length
'request.Headers.Add("Authorization", "Will add this later, do not need auth yet")
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteData, 0, byteData.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer.ToString())
Console.ReadKey()
End Sub
End Module
Thank you for your time.
CodePudding user response:
This was a pretty straightforward fix. I switched to using HttpClient() instead!
Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Text
Module WebRequestHealthCheckPost
Public Sub Main()
Dim request As HttpClient = New HttpClient()
Dim url As String = "https://urlname.com"
Dim body As String = "{""query"":""query healthcheckExampleQuery{healthCheck{ok}}"",""variables"":{}}"
Dim content = New StringContent(body, Encoding.UTF8, "application/json")
Dim result = request.PostAsync(url, content)
Console.WriteLine(result.Result)
Console.ReadKey()
End Sub
End Module