Tasos
Tasos

Reputation: 7577

Send a POST request with vb.net gives 400 bad request error

I am not familiar a lot with Vb.Net, but I try to tweak something on an existent project. I have a cURL that try to implement on Vb.Net. I found different answers here and in other forums, but this way is the one I managed to reach

Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
    Dim req As WebRequest = WebRequest.Create(uri)
    req.ContentType = contentType
    req.Method = method
    req.ContentLength = jsonDataBytes.Length


    Dim stream = req.GetRequestStream()
    stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
    stream.Close()

    Dim response = req.GetResponse().GetResponseStream()

    Dim reader As New IO.StreamReader(response)
    Dim res = reader.ReadToEnd()
    reader.Close()
    response.Close()

    Return res
End Function

Dim postData As String = String.Format("text={0}", title)           
Dim data = Encoding.UTF8.GetBytes(postData)
Dim uri = New Uri("https://.....")
Dim slackResponse = SendRequest(uri, data, "application/json", "POST")

And this is the error I get:

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

If I comment out the SendRequest function, I got an error during calling that, so I guess it is on that part.

Not able to debug more. Any ideas?

Upvotes: 1

Views: 3955

Answers (2)

Pablo Varela
Pablo Varela

Reputation: 648

I solved this long time ago by adding.

request.ContentType = "application/x-www-form-urlencoded"

Upvotes: 1

GMan80013
GMan80013

Reputation: 536

In order to debug more, you need to catch the WebException. WebExceptions have a response object that may contain more information.

Dim response as WebResponse

Try
   response = req.GetResponse().GetResponseStream()
Catch ex As Net.WebException
   If ex.Response IsNot Nothing Then
      response = ex.Response
   End If
End Try

This could be a problem with your URL parameters but many sites also return this class of error when there is a problem in the json content of the request.

Upvotes: 1

Related Questions