Post JSON on URL HTTP Web Request with VB.NET - json

I am using an online NLP API called Wit.ai. I am sending an http web request, and I get a response, and that all works perfectly fine. However, now I need to know how to POST this JSON:
{
"state": "email_or_text"
}
As an addition to this code:
Function getJson()
Dim editedText As String = TextBox1.Text.Replace(" ", "%20")
Dim myHttpWebRequest = CType(WebRequest.Create("https://api.wit.ai/message?v=20140609&q=" + editedText + "&units=metric"), HttpWebRequest)
myHttpWebRequest.Headers.Add("Authorization: Bearer <myauthcode>")
Dim myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Dim myWebSource As New StreamReader(myHttpWebResponse.GetResponseStream())
Dim myPageSource As String = myWebSource.ReadToEnd()
Return myPageSource
End Function
Thanks for your help!

Check this code at http://dotnetpad.com/9O883hmI
it has a quick example of a POST method that can get you started on posting your JSON.
Modify the URL and the content string and hit Run and see the results!

Related

Request to send json with token returns token validation error

When sending the request as a JSON, I get the error "Can't check the token validity." Previously, I obtained the token, which is stored in a variable. The statusCode: OK {200}.
What I observe with the error that is displayed is that the json cannot be sent because the token is not being validated. However, if I do the tests in Postman with the token and the JSON, the result is correct. I am using the RestSharp/106.15.0.0 library, which is the same one with which I obtained the token.
I have tried adding other lines of code, like
request2.AddBody(MyJson)
request2.AddHeader("Cache-Control", "no-cache")
I have carried out the tests in postman which are satisfactory
The code in VB.NET 2015 that I have developed is the following:
Dim client = New RestClient(Var_URLWS)
Dim request2 = New RestRequest(Method.POST)
request2.AddHeader("Content-Type", "application/json")
request2.AddHeader("Authorization", "Mybearer " & MyToken)
request2.AddJsonBody(MyJson, "application/json")
Dim response2 As RestResponse = client.Execute(request2)

Visual Basic - HTTPClient and API Request Issue

Good morning,
As a returning developer (I've been in management for a long time!), I've been tasked with developing a module for our proprietary financial system (Visual Basic/ SQL Server) that will read large .CSV files containing customer information, convert them into JSON format, then submit them to an external party for processing via that company's API.
The conversion part was easy and I'm almost ready to go with it, but I can't establish connectivity to the external API.
There are two parts to the process: -
Submit login details (obfuscated here) {"username": "MadeUpUser","password": "Y66***uYj6%%YY"} and receive a Bearer Token from the API
Submit JSON format customer info to API endpoint, using Bearer Token, receive confirmation
I've submitted both the login creds and my JSON-format data to the API via Postman and it works perfectly, however, when I try to login via my VB app using the HTTPClient class, I'm getting the follow exception (copied from the Exception class properties) :
**HResult = -2146233088
StackTrace = " at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)" & vbCrLf & " at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)"
InnerException = {"The request was aborted: Could not create SSL/TLS secure channel."}**
It's clearly something I'm doing wrong programmatically or something I'm not doing and any help or advice offered will be greatly appreciated.
The code: (AddLogEntry() is a Sub I created to log events to a text file)
Private Async Function PostAsync(ByVal JSONString As String, EndPoint As String) As Task
Dim APIuri As New Uri(EndPoint)
Try
With ZincClient
.BaseAddress = APIuri
.DefaultRequestHeaders.Accept.Clear()
.DefaultRequestHeaders.Accept.Add(New Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
End With
Dim content As New Net.Http.StringContent(JSONString, System.Text.Encoding.UTF8, "application/json")
Dim response As Net.Http.HttpResponseMessage = Await ZincClient.PostAsync(APIuri, content)
Dim result As String = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
AddLogEntry("ERROR! - " & ex.Message)
End Try
Return
End Function

How do I get the body from an HttpWebResponse using Visual Basic (VS2017)

I am having a hell of a time with this project I am working on and could really use your help. I'll try to keep this as concise as possible.
Basically, I have a UI setup that collects user information and sends REST API calls to my call control system. Currently it is working in regards to adding lines, trunks etc.
The problem is I want to see the body of the response coming back from the server. If I have the exception handling look for an OK status code and turn an indicator green, it performs as I have asked.
But I cannot get it to give me the full body of the response like it does when I send the call in POSTMAN.
Here is the response I get back in POSTMAN and would like to get back when I make the API call in VB. I get a Status Code 400 with this in the body.
{
"hint": "The specified Pattern (2952) is already in use by the line owner.",
"details": "Conflicting Pattern",
"code": "P0001",
"message": "invalid_parameter" }
I have tried every combination of search criteria I could find on this site and nothing seems to be working for me. I just don't know what I am doing wrong. Here is a sample of how the request/response is set up now.
Try
'//Setup HTTP connection and modify headers
Dim APIRequest As HttpWebRequest = HttpWebRequest.Create("https://" & CMIP.Text & "/api/v1/" & Custom_Endpoint_URL.Text)
APIRequest.Method = "POST"
APIRequest.Headers.Add("Authorization", "Bearer " + LatestToken.Text)
APIRequest.ContentType = "application/json"
'WebCall.Headers.Add("Prefer", "return=representation") 'Only used for testing purposes
'//Prepare JSON request
Dim bytearray As Byte() = System.Text.Encoding.UTF8.GetBytes(Custom_Body.Text)
APIRequest.ContentLength = bytearray.Length
'//Bypass self-signed cert issue
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
'//Load JSON payload into datastream
Dim datastream As Stream = APIRequest.GetRequestStream()
datastream.Write(bytearray, 0, bytearray.Length)
''//Response
Dim response As WebResponse = APIRequest.GetResponse
Dim responsestream As Stream = response.GetResponseStream
Dim responsereader As New StreamReader(responsestream)
Dim responsereadstring As String = responsereader.ReadToEnd
'//Send response to results window
Response_Box.Text = responsereadstring
Catch ex As WebException
End Try
I wanted to figure this out on my own but I have been at this for a few days now and I'm at the point I am banging my head against the wall.
The HttpWebRequest.GetResponse method throws a WebException when the response has a status code in the 4xx or 5xx range. Based on the information in your question, your API call is returning a status code of 400, so that would trigger the exception. Your Catch block is completely empty, so you are silently ignoring this case. (That is why you should never leave your Catch blocks empty-- you'll never know that something is failing.)
It turns out that the WebException class has a Response property on it (as well as Status), so you can get the data from there. You just need to fill in the Catch block:
Catch ex As WebException
Dim responsestream As Stream = ex.Response.GetResponseStream
Dim responsereader As New StreamReader(responsestream)
Dim responsereadstring As String = responsereader.ReadToEnd
Response_Box.Text = responsereadstring
End Try

Getting json using http web request using get

i'm trying to get a response from an httpwebrequest using get method and content type json..
but i'm getting Cannot send a content-body with this verb-type
here is my code:
Dim objRequest As HttpWebRequest = WebRequest.Create(url)
Dim reqBytes As Byte() = System.Text.UTF8Encoding.UTF8.GetBytes(strPost)
objRequest.Method = "GET"
objRequest.Timeout = "15000"
objRequest.ContentLength = reqBytes.Length
objRequest.ContentType = "application/json; charset=utf-8"
Try
myWriter = objRequest.GetRequestStream()
myWriter.Write(reqBytes, 0, reqBytes.Length)
Catch e As Exception
writetotext(e.toString)
End Try
am i missing something here?
HTTP GET cannot have a message body. Data gets typically passed through the URI path and query string and not through message body for GET requests. For POST, PUT, etc, you should be able to do what you are trying to do in the code above.

Consuming a post method in WCF REST template 40 - JSON

am getting rather frustrated at the lack of information out there on how to post data to a WCF REST method in JSON form. I have tried almost everything out there. Google is just returning purple links at this point...
What I am looking for is a way to send a JSON object to my method so it can shelve all of the data for me. What I am currently trying to get working is below:
The Method header:
[WebInvoke(Method = "POST", UriTemplate = "role/new", ResponseFormat = WebMessageFormat.Json)]
void AddNewRole(Stream streamdata)
The logic from the client app:
string json = JsonConvert.SerializeObject(role);
byte[] buffer = Encoding.UTF8.GetBytes(json);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://IP/InfoService/role/new");
request.Method = "POST";
request.Credentials = new NetworkCredential("", "");
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
sw.Write(json);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Using this method I get an accepted response from the service, but it is a blank response and no new data gets added to the database. Granted, it is possible that there is a problem with my database update methods. Either way, can anyone help me figure out where I am going wrong?
EDIT: I now have fiddler able to test on the test client, and as expected there are problems with my DB queries. Ill post back soon.
EDIT2: Finally worked out the database problems, I have now successfully invoked through fiddler.
EDIT3: Its working now, thanks to nobody.
The code above has been edited, it works.