Teknas
Teknas

Reputation: 559

Error in VB.NET JSON POST request - HTTPWEBREQUEST

i am trying to post json request as following.

I am getting an error on last line. Error message shown at last line.

Dim myReq As HttpWebRequest
Dim myResp1 As HttpWebResponse

myReq = HttpWebRequest.Create("https://pro.mastersindia.co/oauth/access_token")
myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Headers.Add("username", Service_Provider_Username)
myReq.Headers.Add("password", Service_Provider_Password)
myReq.Headers.Add("client_id", client_id)
myReq.Headers.Add("client_secret", client_secret)
myReq.Headers.Add("grant_type", "password")

Dim mystream As Stream = myReq.GetRequestStream
myResp = myReq.GetResponse  ---- here i am getting an error  {"The remote server returned an error: (400) Bad Request."} 

if i send same json to same url via POSTMAN then i do get response. But via vb.net code, i am getting above error.

Am i missing something or doing anything wrong ?

Pls help.

Thanks

[ Following is working in postman, am i missing something in vb.net doing same] [enter image description here]1


enter image description here

Upvotes: 2

Views: 9391

Answers (1)

CruleD
CruleD

Reputation: 1173

Your POST body is empty, you are supposed to put those into body not headers.

There are multiple ways to do it, here is one example.

Imports System.Net
Imports System.Text
Imports Newtonsoft.Json

    Public Class JSON_Post
        Public Property username As String
        Public Property password As String
        Public Property client_id As String
        Public Property client_secret As String
        Public Property grant_type As String
    End Class


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myReq As HttpWebRequest = HttpWebRequest.Create("https://pro.mastersindia.co/oauth/access_token")
        myReq.Method = "POST"
        myReq.ContentType = "application/json"

        Dim NewData As New JSON_Post
        NewData.username = "Service_Provider_Username"
        NewData.password = "Service_Provider_Password"
        NewData.client_id = "client_id"
        NewData.client_secret = "client_secret"
        NewData.grant_type = "password"

        Dim PostString As String = JsonConvert.SerializeObject(NewData)
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostString)
        myReq.ContentLength = byteArray.Length

        Dim dataStream As Stream = myReq.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close() 'sends request

        Dim myResp As HttpWebResponse = myReq.GetResponse()

    End Sub

Your body then looks like:

{"username":"Service_Provider_Username","password":"Service_Provider_Password","client_id":"client_id","client_secret":"client_secret","grant_type":"password"}

Upvotes: 4

Related Questions