Extract cookie from browser and attach to WebRequest - vb.net

I have the following code to send a WebRequest to Betfair, usually this would be sent from a browser and it would send cookie data with it to identify my login, how would I go about attaching the cookie data to this request? (I need to find out how to extract the cookie data first, if anyone can point to any useful articles relating to that it would be much appreciated).
Private Sub Place_Bet(ByVal marketId As String, selectionId As String)
Dim url As Uri
url = New Uri("https://etx.betfair.com/www/etx-json-rpc?_ak=nzIFcwyWhrlwYMrh&alt=json")
Dim json As String = "[{""method"":""ExchangeTransactional/v1.0/place....}]"
Dim data = Encoding.UTF8.GetBytes(json)
Dim result_post = SendRequest(url, data, "application/json", "POST")
MsgBox(result_post)
End Sub
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim response As String
Dim request As WebRequest
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = contentType
request.Method = method
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

Related

Send Json POST Method HttpWebRequest Vb.NET

I already have how to send a JSON by the POST method in Vb.NET, here I leave the code:
Dim request As HttpWebRequest = HttpWebRequest.Create("myurl")
request.Method = "POST"
request.ContentType = "application/json"
request.Headers.Add("authorization", "Bearer 80mgkm6D60OtY16pzs93WoYmx2kzTgf3CELERMVg")
Dim PostString As String = JsonConvert.SerializeObject(MyClase)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostString)
request.ContentLength = byteArray.Length
Dim dataStream1 As Stream = request.GetRequestStream()
dataStream1.Write(byteArray, 0, byteArray.Length)
dataStream1.Close() 'sends request
Question: Is there a simpler way (less code) to do the same thing.
I thank you very much
Question: Is there a simpler way (less code) to do the same thing.
httpClient is what you should be using for new development. Note that HttpClient should NOT be wrapped in a using block.
Public client as new HttpClient()
Public Function makeHttpRequest()
Try
client.DefaultRequestHeaders.Add("HEADERNAME", "HEADERVALUE")
Using response As HttpResponseMessage = Await client.PostAsync("url", new StringContent("YourJsonString", Encoding.UTF8, "application/json"))
Dim responseBody As String = Await response.Content.ReadAsStringAsync()
End Using
Catch e As HttpRequestException
'handle exceptions
End Try
End function
Thank you very much it was solved with the HttpClient library
In the previous way, the error 422 came out in the API server and the JSON was not processed
Dim client As HttpClient = New HttpClient()
Dim request_json = MyJSON
Dim content = New StringContent(request_json, Encoding.UTF8, "application/json")
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", myToken)
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim result = client.PostAsync("myurl", content)
Dim result_Json_string = result.Result.Content.ReadAsStringAsync()
Thank you very much for your advice.

How to send raw json data to put method in vb.net?

i am try send raw data into PUT method , but i am getting error as "The remote server returned an error: (502) Bad Gateway"
But same data i try to use in Postman Agent, its working.
What i tried
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
req.Headers.Add("x-api-key:xxxxxY0tZN55jbXnY05Oxxxxx")
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Calling function
Dim postdata As String = "[{barcod:A0000041},{barcode:A0000113}]"
Dim data = Encoding.UTF8.GetBytes(postdata)
Dim Uri As New Uri("https://sample.com/xxxxx/xxxxx?funcName=UpdateBaarcode")
Dim result_post = SendRequest(Uri, data, "text/plain", "PUT")
What i missing , pls reply.
Regards,
Aravind
For REST API
I use WebRequest using DirectCast.
It's been so long I can't remember why. TT
Try like the code below.
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As HttpWebRequest= DirectCast(WebRequest.Create(uri), HttpWebRequest)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
req.Headers.Add("x-api-key:xxxxxY0tZN55jbXnY05Oxxxxx")
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = DirectCast(req.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function

API-Problem - POST Json-String with httpClient in VB.net

I want to POST json values via httpClient into an API. Unfortunately I am quite a beginner and can't handle it.
GET works perfectly:
here the code for GET:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
' Wird für https-Requests benötigt
System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim s As String
s = reader.ReadToEnd
Return s
But how do I realize POST?
My API-URL looks like this:
https://mydomaine.net/api/auth?token=467445892587458542...
an i will send an JSON-String {"test":"value1":"test1":"value2"}
I've been working on this problem for many hours.
Can someone please help ???
and here is the code that works
Public Function PostRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim response As String
Dim request As HttpWebRequest
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = contentType
request.Method = method
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

WebRequest with Bearer Authorization in VB.NET

I would need to send a POST request to a remote server, which requires a Bearer Authorization.
this is my VB.NET code:
Public Shared Function syncAsana() As String
Dim result As String
Try
Dim token As String = "TOKEN"
Dim uri As String = "https://URL/api/1.0/tasks"
Dim postData As String = "assignee=email&notes=TEST_NOTES&name=NOME 1&projects=123985"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim request As WebRequest = WebRequest.Create(uri)
request.Method = "POST"
request.PreAuthenticate = True
request.Headers.Add("Authorization", "Bearer " & token)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Using dataStream1 As Stream = response.GetResponseStream()
................
result = responseFromServer
End Using
response.Close()
Catch ex As Exception
result = ex.Message
End Try
Return result
End Function
the problem is that I always get the error The underlying connection was closed: An unexpected error occurred on a receive
the same request made with jquery / ajax or with curl works.
I have tried both from the local server launched by visual studio, and by putting the code on the production server.
could you tell me where i'm wrong?

Error trying to Create ASANA Project in VB.NET

I am getting an error:
400 Bad request
when trying to create a project via vb.net in asana.
Note: The ApiKey I am using works when I use it in other vb.net code to get the list of workspaces which is where I got my workspace ID.
Here is my code; I would be grateful for any insight...
Public Sub main()
Dim address As Uri
address = New Uri("https://app.asana.com/api/1.0/projects")
Dim ApiKey As String
ApiKey = "<my api key>"
Dim basicAuthenticationString As String
basicAuthenticationString = Convert.ToBase64String(New UTF8Encoding().GetBytes(ApiKey + ":"))
' Create the web request
Dim request As HttpWebRequest
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
request.Headers("Authorization") = "Basic " & basicAuthenticationString
request.Method = "POST"
request.ContentType = "application/json"
Dim postData As String = "{""data"":[{""name"":""Randy Test Project"",""notes"":""Randy Test Project Notes"",""workspace"":5272875888767}]}"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As HttpWebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
reader.Close()
dataStream.Close()
response.Close()
Exit Sub
End Sub
I was able to figure it out, My address needed to be:
Dim address As Uri = New Uri("app.asana.com/api/1.0/teams/22956925957833/projects")
Then my postData needed to be:
Dim postData As String = "{""data"":{""name"":""Randy Test Project"",""notes"":""Randy Test Project Notes""}}"
Alternatively, you can specify the team or workspace in the post data. When you get a 400 Bad Request the body of the error response will tell you which fields were actually missing/invalid.