VB.Net 401 Unauthorized HTTP Web Request - vb.net

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 ...

Related

access API on imagoxt

i must download some information from API exposed by a server, but whit information in my hand i'm very in difficult.
my code :
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim address As Uri
Dim data As StringBuilder
Dim byteData() As Byte
Dim postStream As Stream = Nothing
address = New Uri("https://www.xxxxxxx.com/api/ajax/widget/refreshWidget")
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
request.Method = "POST"
request.Headers("Authorization") = "Bearer " & "owvNGiOautorizzazoGDNHVGpSO2xcVzE8207JqnjNj"
request.Accept = "application/json"
request.ContentType = "multipart/form-data"
request.Host = "www.xxxxxxx.com"
request.ContentType = "application/x-www-form-urlencoded"
request.Headers.Add("userid", "238")
request.Headers.Add("usernodeid", "1036")
request.Headers.Add("dashboardid", "589")
request.Headers.Add("widgetid", "6699")
data = New StringBuilder()
'data.Append("type: " & HttpUtility.UrlEncode("datatable"))
data.Append(body) 'HttpUtility.UrlEncode(body))
byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
request.ContentLength = byteData.Length
Try
postStream = request.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
Finally
If Not postStream Is Nothing Then postStream.Close()
End Try
Try
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Debug.Print(reader.ReadToEnd())
Finally
If Not response Is Nothing Then response.Close()
End Try
with this code i can access to API whit no error,
but i can't receive anythings.

API-Problem - POST Json-String with httpClient in VB.net

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

WebRequest with Bearer Authorization in VB.NET

I would need to send a POST request to a remote server, which requires a Bearer Authorization.
this is my VB.NET code:
Public Shared Function syncAsana() As String
Dim result As String
Try
Dim token As String = "TOKEN"
Dim uri As String = "https://URL/api/1.0/tasks"
Dim postData As String = "assignee=email&notes=TEST_NOTES&name=NOME 1&projects=123985"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim request As WebRequest = WebRequest.Create(uri)
request.Method = "POST"
request.PreAuthenticate = True
request.Headers.Add("Authorization", "Bearer " & token)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Using dataStream1 As Stream = response.GetResponseStream()
................
result = responseFromServer
End Using
response.Close()
Catch ex As Exception
result = ex.Message
End Try
Return result
End Function
the problem is that I always get the error The underlying connection was closed: An unexpected error occurred on a receive
the same request made with jquery / ajax or with curl works.
I have tried both from the local server launched by visual studio, and by putting the code on the production server.
could you tell me where i'm wrong?

PayPal Get Access Token vb.net The request was aborted: Could not create SSL/TLS secure channel

I have a few questions on calling Grant Access Token API of PayPal, below is my code:
Public Function testAPI() As String
Dim data As StringBuilder
Dim byteData() As Byte
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim postStream As Stream = Nothing
Dim reader As StreamReader
Dim Result As String = ""
request = DirectCast(WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token"), HttpWebRequest)
request.Headers.Add("Username", "XXXXXXXXXX")
request.Headers.Add("Password", "XXXXXXXXXX")
data = New StringBuilder("{""grant_type"":""client_credentials""}")
request.ContentType = "application/x-www-form-urlencoded"
request.Method = WebRequestMethods.Http.Post
byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
request.ContentLength = byteData.Length
postStream = request.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
If Not postStream Is Nothing Then postStream.Close()
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Result = reader.ReadToEnd().ToString
Return Result
End Function
Am I passing Username and Password in right way?
Am I passing "grant_type":"client_credentials" in right way?
I keep getting error: The request was aborted: Could not create SSL/TLS secure channel. I have tried to add some code that I searched from google:
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
request.ProtocolVersion = HttpVersion.Version11
But it still failed and return same error message. Please help.

Error trying to Create ASANA Project in VB.NET

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.