Get a token from a rest api with vbnet. Method POST - vb.net

I am trying to get a token from a ws but so far I have not succeeded.
From postman if I get the token but from my vbnet application no.
The code I use in vbnet is:
Dim client = New RestClient("https://xxxxxxxx.com/IntegrationAPI_2/api/login")
Dim request2 = New RestRequest(Method.POST)
request2.AddParameter("application/json", ParameterType.RequestBody)
request2.RequestFormat = DataFormat.Json
request2.AddParameter("Username", UserVar)
request2.AddParameter("Password", PasswVar)
Dim response2 As RestResponse = client.Execute(request2)
The result obtained in vbnet in statuscode is 0, but in postman it is 200 ok
I am programming in visual studio 2015. Thanks

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls
URLSERVICE += "?username=" & User & "&password=" & Passw
Dim client = New RestClient("" & URLSERVICE & "")
Dim request = New RestRequest(Method.POST)
request.AddHeader("Content-Type", "application/json")
request.RequestFormat = DataFormat.Json
Dim response As RestResponse = client.Execute(request)

Related

I created this code in Visual.Net and it gives an error message This is the error

I created this code in VB.Net and it gives an error message. This is the error in this sentence Dim resp As Dynamic = JObject.Parse(response.Content).
Private Function GetBearerToken() As String
Try
Dim client = New RestClient(Config_class.tokenurl)
Dim request = New RestRequest(Method.POST)
request.AddHeader("cache-control", "no-cache")
request.AddHeader("content-type", "application/x-www-form-urlencoded")
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=" & client_id & "&client_secret=" + client_secret, ParameterType.RequestBody)
Dim response As IRestResponse = client.Execute(request)
Dim resp As Dynamic = JObject.Parse(response.Content)
Dim token As String = resp.access_token
Return token
Catch ex As Exception
End Try
Return ""
End Function
Private Function GetBearerToken() As String
Try
Dim client = New RestClient(Config_class.tokenurl)
Dim request = New RestRequest(Method.POST)
request.AddHeader("cache-control", "no-cache")
request.AddHeader("content-type", "application/x-www-form-urlencoded")
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=" & client_id & "&client_secret=" + client_secret, ParameterType.RequestBody)
Dim response As IRestResponse = client.Execute(request)
Dim resp As Dynamic = JObject.Parse(response.Content)
Dim token As String = resp.access_token
Return token
Catch ex As Exception
End Try
Return ""
End Function
What is 'Dynamic'? Try 'JObject' as the type, according to the documentation for JObject:
Dim resp As JObject = JObject.Parse(response.Content)

VB.NET 401 Unauthorized error in PayPal OAuth API

I'm trying to get an access token back from PayPals OAuth API, I can get it back with curl but need to get the code through vb.NET. I always get a 401 unauthorized response but can't see why. I'm using the following code:
Dim uri as new Uri("https://api-m.sandbox.paypal.com/v1/oauth2/token")
Dim wClientID As String = "client ID"
Dim wClientSecret As String = "Client Secret"
Dim data as string = "grant_type=client_credentials"
Dim dataByte as Byte()
ServicePointManager.Expect100Continue = true
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
request = WebRequest.Create(uri)
request.Headers.Add("Username", wClientID)
request.Headers.Add("Password", wClientSecret)
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " & wClientID & ":" & wClientSecret)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"
dataByte = Encoding.UTF8.GetBytes(data)
Using requestStream = request.GetRequestStream
requestStream.Write(dataByte, 0, dataByte.Length)
requestStream.Close()
End Using
Any help would be appreciated, I've triple checked the client id and secret, both are definitely correct
You need to Base64 encode the clientid:secret string for HTTP basic authentication. Curl does this for you.

Creating new tasks with the Wrike API and VB.net

I'm having trouble creating new Wrike tasks using VB.net and the Wrike API. I however, am able to connect to Wrike to GET a list of folders so I know I'm able to successfully authenticate.
Link to task creation docs:
https://developers.wrike.com/documentation/api/methods/create-task
The only required field is "Title"
Dim accessToken As String = API_Token
Dim apiVersion As String = "v4"
Dim ApiBaseUrl As String = "https://www.wrike.com"
Dim folderID As String = "Some Folder ID Here"
Dim address As String = ApiBaseUrl & "/api/" & apiVersion & "/folders/" & folderID & "/tasks"
Dim result As String
Dim task_str_ As String = "importance=Normal&description=Test task description&dates={""start"":""2019-07-24"",""due"":""2019-07-30""}&title=Task Created With VS&status=Active"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "PUT"
request.ContentType = "application/json"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write(task_str_)
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch ex As Exception
TextBox1.Text = ex.ToString
End Try
Here is the error I'm receiving:
System.Net.WebException: The remote server returned an error: (400) Bad Request
Once I made the suggested changes, everything works good.
Dim accessToken As String = API_Token
Dim apiVersion As String = "v4"
Dim ApiBaseUrl As String = "https://www.wrike.com"
Dim folderID As String = "Some Folder ID Here"
Dim address As String = ApiBaseUrl & "/api/" & apiVersion & "/folders/" & folderID & "/tasks"
Dim result As String
Dim task_str_ As String = "importance=Normal&description=Test task description&dates={""start"":""2019-07-24"",""due"":""2019-07-30""}&title=Task Created With VS&status=Active"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "POST"
request.ContentLength = task_str_.Length
request.ContentType = "application/x-www-form-urlencoded"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write(task_str_)
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch ex As Exception
TextBox1.Text = ex.ToString
End Try

response : unauthorized in Swagger via RestSharp

I need to use an API from Swagger that sends email but I am having a problem in authorization I passed the token but still the result is Unauthorized.
I use the code below.
`Dim url = "test123/test.com" (can't include the actual)
Dim apiKey = "12312"
Dim apiPassword = "12312"
Dim client = New RestClient(url)
Dim request = New RestRequest("token", Method.POST)
request.Parameters.Clear()
request.AddParameter("grant_type", "password")
request.AddParameter("username", apiKey)
request.AddParameter("password", apiPassword)
Dim response As IRestResponse = client.Execute(request)
_pristrKey = response.Content
Return JsonConvert.DeserializeObject(response.Content)`
Now I have the Token in _pristrKey
Then I do this for email sending.
`Dim url = "test123/test.com"
Dim client = New RestClient(url)
Dim request = New RestRequest("api/email", Method.POST)
request.Parameters.Clear()
request.AddHeader("accept", "application/json")
request.AddParameter("Authorization", String.Format($"Bearer " +
_pristrKey), ParameterType.HttpHeader)
request.AddHeader("Content-Type", "application/json")
Dim apiInput = New With {Key .bulkId = "123", Key .from =
"test123#gmail.com", Key .subject = "Test", Key .text = "Test123", Key
.to = "test321#gmail.com"}
request.AddParameter("application/json",
JsonConvert.SerializeObject(apiInput), ParameterType.RequestBody)
request.RequestFormat = DataFormat.Json
Dim response As IRestResponse = client.Execute(request)`
Actual Output: response = "StatusCode: Unauthorized, Content-Type: , Content-Length: 0)"
This error happens because your token is invalid check your token if you got it right, also check for extra double quote(") in the token. I have encounter this in vb.net just use:
.Replace("""", "").Trim()

RestSharp response forbidden

I trying get a simple request to https://c-cex.com/t/prices.json
If i use this url in browser the correct response is showed , but if i make the same request using RestRequest i receive the 403 error Forbidden in all times. i trying HttpClient,WebRequest i get the same error
I put the header with user-agent, no cache and a lot of another values but did not work
Any ideas about this problem?
Dim url As String = "https://c-cex.com/t/prices.json"
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
Dim response = client.Execute(request)
Updated code with apisign request
Dim nonce As String = CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString
Dim url As String = "https://c-cex.com/t/api.html?a=getbalance&currency=BTC&apikey=" & API_KEY & "&nonce=" & nonce
Dim keybytes() = UnicodeEncoding.ASCII.GetBytes(API_SECRET)
Dim hs As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(keybytes)
Dim urlbytes() = UnicodeEncoding.ASCII.GetBytes(url)
Dim sh() = hs.ComputeHash(urlbytes)
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
request.AddHeader("Cache-Control", "no-cache")
request.AddHeader("apisign", HttpUtility.UrlEncode(ToHexString(sh)))
Dim response = client.Execute(request)
I am getting the response without providing the header information and It looks given piece of code is working correctly for me in VB and C#.As a best practice, base URL needs to be specified in RestClient and relative URL in RestRequest.
Please recheck without adding the request header information
VB:
Imports RestSharp
Module Module1
Sub Main()
Dim host As String = "https://c-cex.com"
Dim endpoit As String = "t/prices.json"
Dim client As New RestSharp.RestClient(host)
Dim request = New RestRequest(endpoit, Method.GET)
Dim response = client.Execute(request)
Console.WriteLine("Response Body " + response.Content)
Console.WriteLine("Response Code " + response.StatusDescription)
End Sub
End Module
C#:
String host = "https://c-cex.com";
String endpoint = "t/prices.json";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.GET);
var response = _restClient.Execute(request);
Console.WriteLine("Response Body :"+response.Content);
Console.WriteLine("Response Status Code :" + response.StatusDescription);