Search code examples
jsonvb.netcurlhttpwebrequest

Trying to send CURL Command using VB.Net and HttpWebRequest - Error 403 Forbidden


I have been trying to send this CURL Command below, and tried a few examples out there but none of them work, as I need to send the username:password and not sure if this is a HEADER and also how to send the BODY of the GET Request. Just looking for a bit of an example which sends user:password as can't find one anywhere?

curl --data {"version":"1.1","method":"room_verify","params":{"account":{"type":"room","value":"0"}}} --user test:test http://ressrv.worldweb.com:8001/json_pos_generic/22

Here is my Code for this:

        Dim url As String = "http://ressrv.worldweb.com:8001/json_pos_generic/22"
    Dim wrq = CType(Net.WebRequest.Create(url), HttpWebRequest)
        Dim postString As String = "{""version"":""1.1"",""method"":""room_verify"",""params"":{""account"":{""type"":""room"",""value"":""0""}}}"

        wrq.Method = "POST"
        wrq.ContentType = "application/json"
        wrq.ContentLength = postString.Length
        wrq.Credentials = New NetworkCredential("test", "test")


    Dim wrqWriter As New StreamWriter(wrq.GetRequestStream())
    wrqWriter.Write(postString)
    wrqWriter.Close()

    Dim responseReader As New StreamReader(wrq.GetResponse().GetResponseStream())
        Dim responseData As String = responseReader.ReadToEnd()

Any Help or Guidance would be much appreciated ...


Solution

  • OK, I found an answer after 2 days of trying to get this sorted and although I used a slightly different bit of code, I think this was all down to not having my credentials converted to Base64 which I am now going to research into why this is required. I found this answer from another article here Curl request equivalent in VB.NET

                Dim myReq As HttpWebRequest
            Dim myResp As HttpWebResponse
    
            myReq = HttpWebRequest.Create("http://ressrv.worldweb.com:8001/json_pos_generic/22")
    
            myReq.Method = "POST"
            myReq.ContentType = "application/json"
            myReq.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes("test:test")))
            Dim myData As String = "{""version"":""1.1"",""method"":""room_verify"",""params"":{""account"":{""type"":""room"",""value"":""0""}}}"
            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)
            Dim myText As String
            myText = myreader.ReadToEnd
    
            MsgBox(myText)
    

    Thanks Anyway !!