r/visualbasic • • Sep 17 '19

VB.NET Help Having problems processing body of 400 Bad Request

Hi All,

I have an issue that I don't quite know where to go.I'm using a httpwebrequest to post data to a Restful API. Which is mostly working.

If I have a successful post I receive a response from the server without issue as I expect.

If I post an unsuccessful message to the server I get a 400 bad request and am unable to receive the message body which contains the details of the bad request.

I know the bad request has a body as I've been testing with Postman and am getting the body as I would expect.

    Shared Function callToAPI(ByVal urlStr As String, ByVal payload As String, ByVal method As String, ByVal username As String, ByVal password As String) As String
        'https://MACHINE_NAME:13125/sss/api/v2/members/?externalUser=
        Dim response As String = ""
        Dim authHeaderScheme As String = "Basic"
        Dim authHeaderValue As String = password

        Try
            Dim request As HttpWebRequest = HttpWebRequest.Create(urlStr)
            Dim payloadBytes As Byte() = Encoding.UTF8.GetBytes(payload)
            'request.Method = "POST"
            request.Method = method
            request.ContentType = "application/json"
            request.PreAuthenticate = True
            request.Credentials = New System.Net.NetworkCredential(username, password)
            If Not method = "GET" Then
                'Send the data
                request.ContentLength = payloadBytes.Length()
                Dim outgoingDataStream As System.IO.Stream = request.GetRequestStream()
                outgoingDataStream.Write(payloadBytes, 0, payloadBytes.Length)
                outgoingDataStream.Close()
            End If

            'Get the response
            Dim apiResponse As WebResponse = request.GetResponse()

            Using returnDataStream As System.IO.Stream = apiResponse.GetResponseStream()
                Dim reader As New System.IO.StreamReader(returnDataStream)
                Dim responseFromServer As String = reader.ReadToEnd()
                response = responseFromServer
            End Using
        Catch ex As Exception
            'Catch ex As WebException
            response = ex.Message & vbCrLf
        End Try
        Return response
    End Function
5 Upvotes

2 comments sorted by

2

u/1d3nt Sep 18 '19 edited Sep 18 '19

Before I get started on your code I just felt the need to point something out. From the code you have posted it's pretty clear that you are new to programming, or the minimum Visual Basic. There are so many obvious factors in your code that just give it away. Disposing of IDisposible objects in some instances and then not in others. Legacy Classic Visual Basic code amosngt other things. Now the only reason I am pointing this out which is not a dig is that you are using the HttpWebRequest class. This semi-socket class is not a beginners class, or even an intermediate level class. Web manipulation using sockets in the correct format is not an easy task if you have not done the homework needed.

That said we can move on. What I must stress to you is that Try catch is for exceptional circumstances. Circumstances that are out of our control. You have simply chucked a try block around the whole code. This is not how you handle exceptions. Let's look at TryCast, this will allow us to create a request without throwing an exception. Then we can test against the result by checking if it is nothing. This is graceful and not lazy. One thing that really hurt my eyes was you using an if statement to decide if the same method is either sending a 'get' or a 'post'. Split them into two methods. Make code readable. You will suffer no performance differences by moving each into its own method. This creates readability and will lead you into fewer issues further down the line.

Keep in mind I do not have access to your server so can not dig deeper with testing.

Imports System.IO
Imports System.Net
Imports System.Text

Public Class PostData

    ''' <summary>
    '''     The number of seconds that the HTTP request will wait for a response from the server
    '''     before throwing a Timeout exception.  Default is 30 seconds.
    ''' </summary>
    Private ReadOnly _mTimeoutSeconds As Integer = 30

    ''' <summary>
    '''     The HTTP Status Code (ex. 200, 404) returned by the most recent server request.
    ''' </summary>
    Private _mLastStatusCode As System.Nullable(Of HttpStatusCode)

    ''' <summary>
    '''     Details about the last error experienced. The InnerException may contain more information as well.
    ''' </summary>
    Private _mLastError As Exception

    ''' <summary>
    '''     The most recent HTML source retrieved from the server.
    ''' </summary>
    Private _mLastPageSource As String

    ''' <summary>
    '''     Attempts to login to the server with the supplied username and password.
    ''' </summary>
    ''' <param name="url">Plaintext url</param>
    ''' <param name="username">Plaintext username</param>
    ''' <param name="password">Plaintext password</param>
    ''' <returns>True if successful, otherwise False.</returns>
    Public Function TryLogin(url As String, username As String, password As String) As Boolean
        _mLastStatusCode = Nothing
        _mLastError = Nothing

        Dim loginUri As New Uri(url)
        Dim loginRequest As HttpWebRequest = TryCast(HttpWebRequest.Create(loginUri), HttpWebRequest)

        If loginRequest Is Nothing Then
            _mLastError = New Exception($"Failed to create HttpWebRequest for '{loginUri.ToString()}.")
            Return False
        End If

        Dim someSuspectPayload As String = "Nothing to see for now"
        Dim someSuspectPayloadBuffer As Byte() = Encoding.ASCII.GetBytes(someSuspectPayload)

        loginRequest.Timeout = _mTimeoutSeconds * 1000
        loginRequest.Method = "post"
        loginRequest.ContentType = "application/x-www-form-urlencoded"
        loginRequest.ContentLength = someSuspectPayloadBuffer.Length
        loginRequest.PreAuthenticate = True
        loginRequest.Credentials = New NetworkCredential(username, password)

        Using requestStream As Stream = loginRequest.GetRequestStream()
            requestStream.Write(someSuspectPayloadBuffer, 0, someSuspectPayloadBuffer.Length)
            requestStream.Close()
        End Using

        Dim loginResponse As HttpWebResponse

        Try
            loginResponse = TryCast(loginRequest.GetResponse(), HttpWebResponse)
        Catch wex As WebException
            _mLastError = New Exception($"Request from '{loginUri.ToString()}' returned Status '{ wex.Status.ToString()}'.  See InnerException for more details.")
            Return False
        Catch ex As Exception
            _mLastError = New Exception($"Failed to get response from '{loginUri.ToString()}'. See InnerException for more details.")
            Return False
        End Try

        _mLastStatusCode = loginResponse.StatusCode

        If loginResponse.StatusCode <> HttpStatusCode.OK Then
            _mLastError = New Exception($"Request from '{ loginUri.ToString()}' returned StatusCode '{CInt(loginResponse.StatusCode)}' ({loginResponse.StatusCode.ToString()}"))
            Return False
        End If

        Dim loginSource As String

        Using resposeStream As Stream = loginResponse.GetResponseStream()
            Using resposeReader As New StreamReader(resposeStream)
                loginSource = resposeReader.ReadToEnd()
            End Using
        End Using

        _mLastPageSource = loginSource

        Return True
    End Function
End Class

1

u/[deleted] Oct 05 '19

[I'm not OP] Woah, I appreciate your effort! I rarely see lengthy and explanatory posts in this subreddit often!