I want to create a post method to read data from body sent by Authorize.Net webhook using VB.Net and i'm new in VB.Net can someone please assist how to read data from body in a Post type method.
To send/receive HTTP requests/responses, typically you would use the HttpClient class (documentation). Specifically in this case you would:
Call the PostAsync method (documentation) to submit the request
Check the response's StatusCode (documentation) to verify that a successful response was returned (presumably an OK - 200 status)
If a successful response was returned, get the response's Content (documentation)
Here is a function (untested) that should get you going in the right direction:
Imports System.Net
Imports System.Net.Http
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports System.Text
'...
Private Async Function SendPost(url As String, data As Object) As Task(Of String)
Dim body = String.Empty
Using client = New HttpClient
Dim content As New StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
Dim response = Await client.PostAsync(url, content)
If (response.StatusCode = HttpStatusCode.OK) Then
body = Await response.Content.ReadAsStringAsync()
End If
End Using
Return body
End Function
Related
I am creating an application in VB.NET 4.7.2 with Visual Studio 2019.
The user must authenticate himself with OpenID Connect.
I already downloaded the IdentityModel Package with the NuGet Package Manager and tried to code the authentication method.
Before First Step: Import libraries
Imports System.Net
Imports IdentityModel.Client
Imports System.Threading.Tasks
First Step: Token Request Data
Function Get_Token As String()
Dim request As TokenRequest = New TokenRequest
request.Address = "https://demo.identityserver.io/connect/token"
request.GrantType = "custom"
request.ClientId = "ClientID"
request.Parameters.Add("parameter1", "value1")
request.Parameters.Add("parameter2", "value2")
Second Step: Call an asynchronous function for the request for the token. I must use an asynchronous function, because the response of the function RequestTokenAsync has Task(Of TokenResponse) as type. My problem here:
Is this the right way? How do I call the async. function, so that the return variable response can be evaluated in the calling function?
Call AsyncCall(request)
The asynchronous function: Does not work and gives the error NullReferenceException
Async Function AsyncCall(rqst As TokenRequest) As Task(Of TokenResponse)
Dim client As Http.HttpClient = New Http.HttpClient()
Dim response As TokenResponse = Await client.RequestTokenAsync(rqst)
Return response
End Function
The asynchronous function returns the variable response to the function Get_Token and the variable is evaluated further:
Third Step: Evaluation of response
Even though the asynchronous function had "Return response" in order to return the variable response to the calling function, the calling function does not recognize response, how can I return the variable response properly?
Get_Token = response.AccessToken
End Function
Can you please help me, or show me any direction?
The IdentityModel coding model changed a while back as follows:
Don't use TokenClient - use HttpClient instead
Use the RequestTokenAsync extension method --> You are doing this already
Also use the TokenRequest object --> You are doing this already
Here is the expected usage
I have a web API2 item that I need to read the 'body' of the incoming request. The client is sending information (via 'PUT') in the body opposed to parameters in the URL. I have been searching for a solution but keep hitting a wall. Can anyone advise how I can get this body text?
Thanks
<HttpOptions>
<Route("v1/cth/test"), AcceptVerbs("PUT", "POST", "OPTIONS")>
Public Function CTHInterface(ByVal passedjson As Object) As String
Return "Hello"
End Function
FYI, I finally managed to get to the body. Hope this helps someone else.
<HttpOptions>
<Route("v1/cth/dev"), AcceptVerbs("PUT", "POST", "OPTIONS")>
Public Function CTHInterfaceDev() As String
Dim CTHStream As New StreamReader(HttpContext.Current.Request.InputStream)
Dim CTHBody As String = CTHStream.ReadToEnd
Return "Hello"
End Function
I am very new to vb/.net and I'm trying to do something that I can do easily in classic vb. I want to get the source html for a webpage from the URL.
I'm using vb.net in Visual Studio Express for Windows 8.
I've read loads of stuff that talk about HttpWebRequest, but I can't get it to work properly.
I did at one point have it returning the html header, but I want to content of the page. Now, I can't even get it back to giving me the header. Ultimately, I want to process the html returned which I'll do (to begin with) the old-fashioned way and process the returned html as a string, but for now I'd like to just get the page.
The code I've got is:
Dim URL As String = "http://www.crayola.com/"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(New Uri(URL))
txtHTML.Text = request.GetRequestStreamAsync().ToString()
Can anyone help me with an example to get me going please?
You're trying to use an Async method in a synchronous way, which won't make any sense. If you're using .NET 4.5, you can try marking the calling method with Async and then using the Await keyword when calling GetRequestStreamAsync.
Public Sub MyDownloaderMethod()
Dim URL As String = "http://www.crayola.com/"
Dim request As System.Net.HttpWebRequest
= System.Net.HttpWebRequest.Create(New Uri(URL))
' Use the Await keyword wait for the async task to complete.
Dim response = request.GetResponseAsync()
txtHTML.Text = response.GetResponseStream().ToString()
End Function
See the following MSDN article for more information on async programming with the Await keyword: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
Edit
You are receiving your error because you're trying to get the Request stream (what you send the server), and what you really want is the Response stream (what the server sends back to you). I've updated my code to get the WebResponse from your WebRequest and then retrieve the stream from that.
Public Shared Function GetWebPageString(ByVal address As Uri) As String
Using client As New Net.WebClient()
Return client.DownloadString(address)
End Using
End Function
There is also DownloadStringAsync if you don't want to block
request.GetRequestStreamAsync() is probably not a method. I think you're cribbing code from a site where someone wrote their own add-on methods to HttpWebRequest. Try request.GetResponse() to return a response object, then in the response object you can inspect the stream and convert it to text if you need to.
This worked for me in VB.Net 4.5
Public Async Sub GetHTML()
Dim PageHTML as string
Dim client As New HttpClient
Dim getStringTask As Task(Of String) = client.GetStringAsync(PageURL)
PageHTML = Await getStringTask
MsgBox(PageHTML)
End Sub
does anybody has an idea how I can perform an asynchronus Post Request in VB.Net for Windows Phone 8?
I tried a lot but nothing worked... also this http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.begingetrequeststream.aspx didn't work.
Thanks a lot.
I had to figure this out for myself a while ago. Let me see what I can do to help.
Posting a web request is actually simpler than that link shows. Here's what I do.
First, I create a MultipartFormDataContent:
Dim form as New MultipartFormDataContent()
Next, I add each string I want to send like this:
form.Add(New StringContent("String to sent"), "name of the string you are sending")
Next, create a HttpClient:
Dim httpClient as HttpClient = new HttpClient()
Next, we'll create a HttpResponseMessage and post your information to the url of your choice:
Dim response as HttpResponseMessage = Await httpClient.PostAsync("www.yoururl.com/wherever", form)
Then, I usually need the response as a string, so I read the response to a string:
Dim responseString as String = Await response.Content.ReadAsStringAsync()
This will give you the response you wanted, if that's what you wanted.
Here's an example of a method I use:
Public Async Function GetItems() As Task
Dim getUrl As String = "https://myapiurl.com/v3/get"
Dim responseText As String = String.Empty
Dim detailType As String = "complete"
Try
Dim httpClient As HttpClient = New HttpClient()
Dim form As New MultipartFormDataContent()
form.Add(New StringContent(roamingSettings.Values("ConsumerKey").ToString()), "consumer_key")
form.Add(New StringContent(roamingSettings.Values("access_token").ToString()), "access_token")
form.Add(New StringContent(detailType.ToString()), "detailType")
Dim response As HttpResponseMessage = Await httpClient.PostAsync(getUrl, form)
responseText = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
End Try
End Function
If you aren't using the Http client libraries, you need to install them like this:
What you need to do to use the HttpClient, is to navigate in Visual Studio, go to Tools->Library Package Manager->Manage Nuget Packages for this solution. When there, search the online section for HttpClient and make sure you have "Include Prerelease" selected in the listbox above the results. (Default is set to "Stable Only")
Then install the package with the ID of Microsoft.Net.Http
Then you'll need to add an Import statement at the beginning of the document you are using it in.
Let me know if this is what you were looking for.
Thanks,
SonofNun
Really having trouble trying to implement this in my controller. Essentially as it stands I have a controller than when it completes passes the user to a URL as below:
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function
However I am trying to implement the functionality to send an SMS each time this controller is called and have got this working with a URL like (made up without username or password):
http://go.bulksms.com:1557/send?username=fred&message=hello
This needs to be accessed via an HTTP post request. I understand I can return this URL in the 'Return Redirect' above but I want both to happen (the redirect and the post on this link sending the SMS) and ideally I want the user to be redirected to the page as it happens now but the SMS to be sent in the background. How would I implement this?
Try this. New code is added between two comment line. You can also consult this url for details, if it's a POST you might have to pass some form data, it's all described in the link above.:
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
'Sending SMS here: (start)
Dim request as WebRequest = WebRequest.Create("http://go.bulksms.com:1557/send?username=fred&message=hello")
request.Method = "POST"
Dim response As WebResponse = request.GetResponse()
'end
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function
Redirect is always a GET request
for posting to the different URL , You need to call it from your code using HttpWebRequest class.