Results 1 to 6 of 6

Thread: CURL request in VB.net

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2012
    Posts
    158

    CURL request in VB.net

    I'm trying to send a CURL request, but appear to be having some issues with my header and hope someone can help...

    Code:
    curl -u 'myusername-test:1815dff0d321430378567bc84963ecd06f71d10f' 'https://api.dev.thewebsite.com/v4/domains' -X POST -H 'Content-Type: application/json' --data '{"domain":{"domainName":"example.org"},"purchasePrice":12.99}'
    Here is my code:
    Code:
    Try
    Dim myReq As HttpWebRequest
    Dim myResp As HttpWebResponse
    Dim myUsername As String = "myusername-test:1815dff0d321430378567bc84963ecd06f71d10f"
    
    myReq = HttpWebRequest.Create("https://api.dev.thewebsite.com/v4/domains")
    
    myReq.Method = "POST"
    myReq.ContentType = "application/json"
    myReq.Headers.Add(myUsername)
    Dim myData As String = "{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}"
    myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
    myResp = myReq.GetResponse
    Dim myreader As New System.IO.StreamReader(myResp.GetResponseStream)
    WebResponse = myreader.ReadToEnd
    Catch ex As Exception
    txtLog.AppendText("THREAD EXCEPTION at " & TimeOfDay & " with error: " & ex.Message & vbCrLf)
    End Try
    This looks to me like it should work, but I keep getting an exception:
    THREAD EXCEPTION at 4:47:46 AM with error: The remote server returned an error: (401) Unauthorized.

    === ADDED ===
    Even changing this line:
    Code:
    myReq.Headers.Add(myUsername)
    to something like this:
    Code:
    myReq.Headers.Add("myusername-test", "1815dff0d321430378567bc84963ecd06f71d10f")
    Also returns the same (401) Unauthorized message.
    Last edited by digitaldrew; Jul 2nd, 2023 at 07:07 AM. Reason: Added to the bottom

  2. #2

    Thread Starter
    Addicted Member
    Join Date
    Nov 2012
    Posts
    158

    Re: CURL request in VB.net

    I made some changes to the code, adding the header name "Authorization" and used the "Basic" authentication scheme to add the `myUsername` to the headers. I've also modified the way the request data is written to the request stream for better readability.

    Here is my new code:
    Code:
    Try
    Dim myReq As HttpWebRequest
    Dim myResp As HttpWebResponse
    Dim myUsername As String = "myusername-test:1815dff0d321430378567bc84963ecd06f71d10f"
    
    myReq = HttpWebRequest.Create("https://api.dev.thewebsite.com/v4/domains")
    
    myReq.Method = "POST"
    myReq.ContentType = "application/json"
    myReq.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes(myUsername)))
    
    Dim myData As String = "{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}"
    Dim dataBytes As Byte() = Encoding.UTF8.GetBytes(myData)
    myReq.GetRequestStream.Write(dataBytes, 0, dataBytes.Length)
    
    myResp = myReq.GetResponse()
    Dim myreader As New System.IO.StreamReader(myResp.GetResponseStream)
    Dim WebResponse As String = myreader.ReadToEnd()
    
    Catch ex As Exception
    txtLog.AppendText("THREAD EXCEPTION at " & TimeOfDay & " with error: " & ex.Message & vbCrLf)
    End Try
    However, this also does not work and gives the following:
    THREAD EXCEPTION at 5:12:24 AM with error: The remote server returned an error: (400) Bad Request.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Nov 2012
    Posts
    158

    Re: CURL request in VB.net

    Here is something else I've tried.....

    ​1) I took my CURL request and used the curl to C# converter to convert it to C#

    2) I took the C# code and used the C# to VB.net converter to convert it to VB.net

    3) That gave me this:
    Code:
    Using httpClient = New HttpClient()
        Using request = New HttpRequestMessage(New HttpMethod("POST"), "https://api.dev.thewebsite.com/v4/domains")
            Dim base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("myusername-test:1815dff0d321430378567bc84963ecd06f71d10f"))
            request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}")
            request.Content = New StringContent("{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}")
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json")
            Dim response = Await httpClient.SendAsync(request)
        End Using
    End Using
    However, this code gives a lot of errors..



    I've done some re-writing, but continue to have issues...
    Code:
                            Dim myUsername As String = "myusername-test:1815dff0d321430378567bc84963ecd06f71d10f"
                            Dim EncodedString As String = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(myUsername))
    
                            Dim httpWebRequest = CType(WebRequest.Create("https://api.dev.thewebsite.com/v4/domains"), HttpWebRequest)
    
                            httpWebRequest.Method = "Post"
                            httpWebRequest.Headers.Add("Authorization: Basic " & EncodedString)
                            httpWebRequest.ContentType = "application/json"
    
                            Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
                                Dim Body As String = "{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}"
                                streamWriter.Write(Body)
                            End Using
    
                            Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
                            Using streamReader = New StreamReader(httpResponse.GetResponseStream())
                                Dim result = streamReader.ReadToEnd()
                                WebResponse = result
                            End Using
    Returns a (400) Bad Request. Since this is a "Bad Request" I can't really tell if that means I'm getting authenticated okay now and the error is maybe in my Body/data?

  4. #4
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,408

    Re: CURL request in VB.net

    Quote Originally Posted by digitaldrew View Post
    Here is something else I've tried.....

    ​1) I took my CURL request and used the curl to C# converter to convert it to C#

    2) I took the C# code and used the C# to VB.net converter to convert it to VB.net

    3) That gave me this:
    Code:
    Using httpClient = New HttpClient()
        Using request = New HttpRequestMessage(New HttpMethod("POST"), "https://api.dev.thewebsite.com/v4/domains")
            Dim base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("myusername-test:1815dff0d321430378567bc84963ecd06f71d10f"))
            request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}")
            request.Content = New StringContent("{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}")
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json")
            Dim response = Await httpClient.SendAsync(request)
        End Using
    End Using
    However, this code gives a lot of errors..



    I've done some re-writing, but continue to have issues...
    Code:
                            Dim myUsername As String = "myusername-test:1815dff0d321430378567bc84963ecd06f71d10f"
                            Dim EncodedString As String = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(myUsername))
    
                            Dim httpWebRequest = CType(WebRequest.Create("https://api.dev.thewebsite.com/v4/domains"), HttpWebRequest)
    
                            httpWebRequest.Method = "Post"
                            httpWebRequest.Headers.Add("Authorization: Basic " & EncodedString)
                            httpWebRequest.ContentType = "application/json"
    
                            Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
                                Dim Body As String = "{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}"
                                streamWriter.Write(Body)
                            End Using
    
                            Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
                            Using streamReader = New StreamReader(httpResponse.GetResponseStream())
                                Dim result = streamReader.ReadToEnd()
                                WebResponse = result
                            End Using
    Returns a (400) Bad Request. Since this is a "Bad Request" I can't really tell if that means I'm getting authenticated okay now and the error is maybe in my Body/data?
    It looks as though a lot of those errors are due to the code missing the relevant using statements - the IDE is offering Potential Fixes, did you try those to see if it solved the problem?

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Nov 2012
    Posts
    158

    Re: CURL request in VB.net

    Thanks for the reply @PlausiblyDamp. I cleaned up the converted code, but it still broke and I wasn't even able to get a response using it.

    Overall, the CURL code really seems pretty small and simple... The user authentication, one thing in the header (content type) and the data. Not really sure where I'm going wrong here. For further context, here is a link to the documentation with the exact example I'm working off of.

    Here is the most updated code I've been messing with, although it's pretty much the same as others I've already shared:
    Code:
    Dim uri As New Uri("https://api.dev.name.com/v4/domains")
    Dim myUsername As String = txtUsername.Text.Trim & ":" & txtApiKey.Text.Trim
    Dim data As String = "{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}"
    Dim dataByte As Byte()
    
    request = WebRequest.Create(uri)
    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes(myUsername)))
    request.ContentType = "application/json"
    request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"
    request.Method = "POST"
    
    dataByte = Encoding.UTF8.GetBytes(data)
    request.GetRequestStream.Write(dataByte, 0, dataByte.Length)
    
    Dim myResp As HttpWebResponse
    myResp = request.GetResponse()
    Dim myreader As New System.IO.StreamReader(myResp.GetResponseStream)
    WebResponse = myreader.ReadToEnd()
    
    MsgBox(WebResponse)
    Just as you might expect, this returns a 400 (Bad Request).. I even tried adding a useragent to see if that would do the trick, but it's the same with or without it. Can't figure out what I'm missing since I'm converting/passing the authorization, including the content type in the header, and my data looks to match exactly as their example shows...

  6. #6
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,657

    Re: CURL request in VB.net

    RESTful clients like insomnia and postman will take a REST request and produce corresponding code for you. The benefit of doing this is that you can test that hitting the endpoint works outside of your .NET environment. Here is what gets generated in C#:
    Code:
    var client = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Post, "https://api.dev.thewebsite.com/v4/domains");
    request.Headers.Add("Authorization", "Basic bXl1c2VybmFtZS10ZXN0OjE4MTVkZmYwZDMyMTQzMDM3ODU2N2JjODQ5NjNlY2QwNmY3MWQxMGY=");
    var content = new StringContent("{\"domain\":{\"domainName\":\"example.org\"},\"purchasePrice\":12.99}", null, "application/json");
    request.Content = content;
    var response = await client.SendAsync(request);
    response.EnsureSuccessStatusCode();
    Console.WriteLine(await response.Content.ReadAsStringAsync());
    Here it is converted to VB.NET:
    Code:
    Dim client = new HttpClient()
    Dim request = new HttpRequestMessage(HttpMethod.Post, "https://api.dev.thewebsite.com/v4/domains")
    request.Headers.Add("Authorization", "Basic bXl1c2VybmFtZS10ZXN0OjE4MTVkZmYwZDMyMTQzMDM3ODU2N2JjODQ5NjNlY2QwNmY3MWQxMGY=")
    Dim content = new StringContent("{""domain"":{""domainName"":""example.org""},""purchasePrice"":12.99}", null, "application/json")
    request.Content = content
    Dim response = await client.SendAsync(request)
    response.EnsureSuccessStatusCode()
    Console.WriteLine(await response.Content.ReadAsStringAsync())
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width