How to call a WebAPI2 from VB.NET - vb.net

I'm trying to call a WebAPI2 api from a legacy VB code.
The API works when called from fiddler or from the AngularJS client.
[Route("CreateMyObject")]
[HttpPost]
public async Task<JsonResult<MyObject>> CreateMyObject([FromUri] int parentId, [FromBody] MyObject object)
Then in the VB code:
Dim apiUri As New Uri(apiUrl & "api/CreateMyObject?parentId=" &
intParentId.ToString())
Dim data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(myObjectInstance))
Dim webRequest As WebRequest = WebRequest.Create(uri)
webRequest.ContentType = "application/json"
webRequest.Method = "POST"
webRequest.ContentLength = data.Length
Dim stream = webRequest.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()
Dim response = webRequest.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
I can only get a 415 response from the API. I tried other content-types as well, but with the same result or server error.
Whatever is wrong with this call seems to be related with the Json body bit, because if I don't send anything in the call body, the parentId gets to the API as it's supposed to.

As Chase Rocker mentioned, try first by initializing jsonDataBytes as
Dim jsonDataBytes As Bytes()
Also verify the json object to make sure it is fine. Use this link http://jsonlint.com/ or for better assistance use Fiddler
instead.

Related

Why would my VB.NET WebRequest suddenly stop working?

A while ago I wrote a programme in VB.NET to use the Betfair Exchange API. It has worked perfectly for months, but overnight on Tuesday it stopped working. I can still log in, but from Wednesday I have been unable to get anything else from the server.
Betfair are investigating, but according to them nobody else seems to be experiencing the same problem - although I'm not sure how many will be using VB.NET.
Below is the function I have been using to obtain data from the API. Like I said it was working on Tuesday night but not from Wednesday morning. Is there anything here which is "not perfect" or "could be better", or perhaps there is some alternative code I could try? Or is there something which might have happened on my pc which has caused the problem?
The programme falls over at the line "dataStream = request.GetRequestStream() ". The error is "Received an unexpected EOF or 0 bytes from the transport stream."
I would be grateful for any advice that anyone could offer. Thank you!
Public Function CreateRequest(ByVal postData As String, Optional ByVal accountsApi As Boolean = False)
Dim Url As String = "https://api.betfair.com/exchange/betting/json-rpc/v1"
If accountsApi Then Url = "https://api.betfair.com/exchange/account/json-rpc/v1"
Dim request As WebRequest = Nothing
Dim dataStream As Stream = Nothing
Dim response As WebResponse = Nothing
Dim strResponseStatus As String = ""
Dim reader As StreamReader = Nothing
Dim responseFromServer As String = ""
Try
request = WebRequest.Create(New Uri(Url))
request.Method = "POST"
request.ContentType = "application/json-rpc"
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
request.Headers.Add("X-Application", appKey)
request.Headers.Add("X-Authentication", sessToken)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData) ' Data to post such as ListEvents, ListMarketCatalogue etc
request.ContentLength = byteArray.Length ' Set the ContentLength property of the WebRequest.
dataStream = request.GetRequestStream() ' Get the request stream.
dataStream.Write(byteArray, 0, byteArray.Length) ' Write the data to the request stream.
dataStream.Close() ' Close the Stream object.
response = request.GetResponse() ' Get the response.
strResponseStatus = CType(response, HttpWebResponse).StatusDescription ' Display the status below if required
dataStream = response.GetResponseStream() ' Get the stream containing content returned by the server.
reader = New StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
responseFromServer = reader.ReadToEnd() ' Read the content.
reader.Close() : dataStream.Close() : response.Close()
Catch ex As Exception
MsgBox("CreateRequest Error" & vbCrLf & ex.Message, MsgBoxStyle.Critical, " Error")
End Try
Return responseFromServer
End Function
I would check that the provider hasn't recently deprecated use of TLS 1.0 (as they should have done before now, in fact).
If so, your code needs to enforce use of TLS 1.1+:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
This only has to be set once, usually in the (static) type initializer or similar.
And I 100% agree with Andrew Mortimer that you should use Using blocks wherever possible. I'd also suggest moving all of your string values into variables or constants to clean things up and keep them maintainable. Eg:
Const ContentType As String = "application/json-rpc"
...
request.ContentType = ContentType
UPDATE
I just found this announcement on their site:
https://forum.developer.betfair.com/forum/developer-program/announcements/33563-tls-1-0-no-longer-supported-from-1st-december-all-betfair-api-endpoints
If you are allowed to use external dependencies within this project I would recommend using RestSharp nuget package it works really well for creating API requests and getting there response without having to use httpclient which gets messy.
Link: https://restsharp.dev/

How do I add grant_type, username and password to API request in VB.net

I'm trying to figure out how to get an authorization token from the BIC - BOXTECH API. I can do it in a program called POSTMAN that helps with API stuff, but I cannot work out how to take what I have in POSTMAN and code it into my VB.NET application. I believe I may need to add a BODY to my HTTPWebRequest but don't know how. Can anyone point me in the right direction. New to API's. Thx.
This is the code I have so far - but missing the way to add:
grant_type=password
username=myemail#somedomain.com
password=mypassword
Public Function GetBoxAPIToken() As String
Try
Dim request As WebRequest = HttpWebRequest.Create($"https://app.bic-boxtech.org/oauth/token")
With request
.Headers.Add("Authorization", $"Basic YmljYXBwOmJpY3NlY3JldGFwcA==")
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
End With
Using response As WebResponse = request.GetResponse()
Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim jsonResponseText As String = streamReader.ReadToEnd()
Dim m As JArray = JArray.Parse(jsonResponseText)
Console.WriteLine(m.Item(0).Item("accessToken"))
Return m.Item(0).Item("accessToken")
End Using
End Using
Catch ex As Exception
'Catch error here...
Return Nothing
End Try
End Function

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?
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.
I solved this long time ago by adding.
request.ContentType = "application/x-www-form-urlencoded"

Trouble with POSTing JSON to endpoint

I'm trying to submit a POST request containing JSON to a given endpoint. However the below code sends me to a login page which is the default functionality for all non-/api endpoints. Because Postman doesn't direct me to the login page but correctly hits the API, I'm assuming the problem is in this C# code.
Dim RemoteUrl As String = "https://my-site.com/api/tournament/results"
Dim result As String = ""
Dim xmlHttpReq As HttpWebRequest = CType(WebRequest.Create(RemoteUrl), HttpWebRequest)
xmlHttpReq.Method = "POST"
xmlHttpReq.ContentType = "application/json"
With (New StreamWriter(xmlHttpReq.GetRequestStream))
.Write(Json)
.Flush()
.Close()
Dim httpResponse As HttpWebResponse = CType(xmlHttpReq.GetResponse(), HttpWebResponse)
With (New StreamReader(httpResponse.GetResponseStream))
result = .ReadToEnd
End With
End With
Any idea what steps I need to take to debug this?

VB.NET - How To Make a Post to Blogspot Using Blogger API V3?

I'm trying to to make a new post through my vb.net application using blogger api.
But I'm fail every time.
Sometimes it's return 403 forbidden error some times Unauthorised error.
Please Help.
Dim mBlogID As String = "5861877551002158183"
Dim AuthToken As String = "AIza......xxxx..........E6g"
Dim post As String = "{""kind"": ""blogger#post"", ""blog"": { ""id"": """ & mBlogID & """}, ""title"": ""abc-title"", ""content"": ""abc-cont""}"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.googleapis.com/blogger/v3/blogs/" & mBlogID & "/posts?key=" & AuthToken), HttpWebRequest)
request.Method = "POST"
request.ContentLength = post.Length
request.ContentType = "application/json"
request.Headers.Add("Authorization: ", AuthToken) '<--- error here
Using requestStream As Stream = request.GetRequestStream()
Dim postBuffer As Byte() = Encoding.ASCII.GetBytes(post)
requestStream.Write(postBuffer, 0, postBuffer.Length)
End Using
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) '<--- Unauthorised error or 403 error here
Using responseStream As Stream = response.GetResponseStream()
Using responseReader As New StreamReader(responseStream)
'Dim json As String = responseReader.ReadToEnd()
'Dim PostURL As String = Regex.Match(json, """url"": ?""(?<id>.+)""").Groups("id").Value
MsgBox(json) 'want to read json response here.
'MsgBox(PostURL)
End Using
End Using
End Using
This code return this error :Specified value has invalid HTTP Header characters.
Parameter name: name
can anybody fix it? I just want to make a new post to blogger and read its URL.
Project Information:-
Platform: Visual Basic 2010
Blogger API Version: V3
I Suggest view this solution. The post has fully explanations.