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.
Related
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
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
I am having different problems when trying to make a POST request to my API, the API works perfectly tested in postman.
I would like to know if anyone sees that I am doing wrong, thank you very much
Dim url As String = "http://0.0.0.0/connect"
Dim dataToPassFromFormData As String = "client_id=1020&client_secret=FF29D58E&grant_type=password&username=admin&password=123"
Dim enc As UTF8Encoding
Dim postdatabytes As Byte()
Dim request As HttpWebRequest = TryCast(WebRequest.Create(url), HttpWebRequest)
enc = New System.Text.UTF8Encoding()
postdatabytes = enc.GetBytes(dataToPassFromFormData)
request.Method = "POST"
request.ContentLength = postdatabytes.Length
Using stream = request.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim receiveStream As Stream = response.GetResponseStream()
Dim readStream As StreamReader = New StreamReader(receiveStream, Encoding.UTF8)
Dim us As user
us = JsonConvert.DeserializeObject(Of user)(readStream.ReadToEnd())
response.Close()
readStream.Close()
Return us.access_token
My api expects these parameters by body / form-data
client_id=1020
client_secret=FF29D58E
grant_type=password
username=admin
password=123
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.
I'm attempting to login to a cPanel using a POST Request in VB.Net. I have the correct credentials when logging in and when posting I still get an 'Unauthorized (401)' response when it should be '301' (analysed using Tamper Data Firefox Add-On). Below is my post request information and function.
Private Function POSTreq(ByVal URL$, ByVal Data$)
Dim tempCookie As New CookieContainer
Dim DataBytes As Byte() = Encoding.ASCII.GetBytes(Data)
Dim Request As HttpWebRequest = TryCast(WebRequest.Create(URL), HttpWebRequest)
Request.Method = "POST"
Request.ContentType = "application/x-www-form-urlencoded"
Request.ContentLength = DataBytes.Length
Dim PostData As Stream = Request.GetRequestStream()
PostData.Write(DataBytes, 0, DataBytes.Length)
PostData.Close()
Dim Response As HttpWebResponse = Request.GetResponse()
Dim ResponseStream As Stream = Response.GetResponseStream()
Dim StreamReader As New StreamReader(ResponseStream)
Dim Text$ = StreamReader.ReadToEnd()
Return Text
End Function
Post URL
http://example.com:2082/login/
Post Data
login_theme=cpanel&user=USERNAME&pass=PASSWORD&goto_uri=%2F
I could reproduce your described behaviour with your code.
If I set the CookieContainer it works on my side, and I was able to log in:
rem ...
Request.CookieContainer = tempCookie
Request.Method = "POST"
rem ... and so on ...
The second Solution would be to just provide the Credentials:
rem ...
Dim myFullUri = new Uri(URL)
Dim myCredentials As New NetworkCredential(Username, Password)
Dim myCache As New CredentialCache()
rem Add the credentials for that specific host and
rem for "Basic" authentication only
myCache.Add(New Uri(myFullUri.Scheme & "://" & myFullUri.Authority), _
"Basic", myCredentials)
Request.Credentials = myCache
Request.CookieContainer = tempCookie
Request.Method = "POST"
rem ... and so on ...