Home > Blockchain >  Reading Rest API Call Response Status Code in VB.NET
Reading Rest API Call Response Status Code in VB.NET

Time:10-19

I am a beginner in the API ecosystem. I am using VB.NET to call API. Code used for the same given below:

        Try
            Dim s As HttpWebRequest
            Dim enc As UTF8Encoding
            Dim postdata As String
            Dim postdatabytes As Byte()

            Dim jo As New JObject
            jo.Add("apiid", objProp.Text7)
            jo.Add("apiData", objProp.Text8)

            postdata = jo.ToString()
            s = HttpWebRequest.Create(objProp.Text6)
            enc = New System.Text.UTF8Encoding()
            postdatabytes = enc.GetBytes(postdata)
            s.Method = "POST"
            s.ContentType = "application/json"
            s.ContentLength = postdatabytes.Length
            s.Headers.Add("user-name", "MjRKQGU1NypQJkxZYVpCdzJZXnpKVENmIXFGQyN6XkI=")
            s.Headers.Add("api-key", "UjMhTDZiUlE1MkhMWmM2RkclJXJhWUJTTWZDeHVEeDQ=")

            Using stream = s.GetRequestStream()
                stream.Write(postdatabytes, 0, postdatabytes.Length)
            End Using
            Dim result = s.GetResponse()

            Dim responsedata As Stream = result.GetResponseStream
            Dim responsereader As StreamReader = New StreamReader(responsedata)
            Dim xResponse = responsereader.ReadToEnd
            Try
                Dim opData = JObject.Parse(xResponse)("apiData").ToString
                objProp = JsonConvert.DeserializeObject(Of default_prop)(opData)
            Catch ex As Exception

            End Try

        Catch myerror As OracleException

            'Status
            objProp.Text5 = "500"
            'Failure Response Message
            objProp.Text11 = "Internal Server Error..."
            db_close()

        End Try

My issue is that I could not find the proper syntax to retrieve API Response Status Code from the response. Request your guidance

CodePudding user response:

With some small changes on your code you can do the trick as follow:

        '....... other code here

        Using stream = s.GetRequestStream()
            stream.Write(postdatabytes, 0, postdatabytes.Length)
        End Using

        Dim result As HttpWebResponse = CType(s.GetResponse(), HttpWebResponse)
        Console.WriteLine(result.StatusCode)
  • Related