I'm trying to submit a POST request containing JSON to a given endpoint. However the below code sends me to a login page which is the default functionality for all non-/api endpoints. Because Postman doesn't direct me to the login page but correctly hits the API, I'm assuming the problem is in this C# code.
Dim RemoteUrl As String = "https://my-site.com/api/tournament/results"
Dim result As String = ""
Dim xmlHttpReq As HttpWebRequest = CType(WebRequest.Create(RemoteUrl), HttpWebRequest)
xmlHttpReq.Method = "POST"
xmlHttpReq.ContentType = "application/json"
With (New StreamWriter(xmlHttpReq.GetRequestStream))
.Write(Json)
.Flush()
.Close()
Dim httpResponse As HttpWebResponse = CType(xmlHttpReq.GetResponse(), HttpWebResponse)
With (New StreamReader(httpResponse.GetResponseStream))
result = .ReadToEnd
End With
End With
Any idea what steps I need to take to debug this?
Related
Im trying to use the Blue Prism object HTTP request to get an access token for further processing the items. However, i couldn't manage to get the token due to the error 'The given key was not present in the dictionary'. I have looked all parameters and still didn't manage to solve the issue. I use a built in visual basic code to get the result as a collection which is later parsed to JSON to get the token.
The underlying visual basic code is:
Dim request As WebRequest = WebRequest.Create(addressURL)
If forcePreAuth Then
'Sometimes a web server will require the authorisation header in the initial request
'In which case we have to add the basic authorization header manually.
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}",username,password))
Dim base64 As String = Convert.ToBase64String(bytes)
request.Headers.Add("Authorization", "Basic " & base64)
Else
If Not String.IsNullOrEmpty(username) AndAlso Not String.IsNullOrEmpty(password) Then
request.Credentials = New NetworkCredential(username,password)
End If
End If
If useProxy Then
Dim proxyURI As New Uri(proxyURL)
Dim proxy As New WebProxy(proxyURI, True)
Dim proxyCred As New NetworkCredential(proxyUsername, proxyPassword)
Dim credCache As New CredentialCache()
credCache.Add(proxyURI, "Basic", proxyCred)
proxy.UseDefaultCredentials = False
proxy.Credentials = credCache
request.Proxy = proxy
End If
request.Method = method
request.ContentType = contentType
Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest)
If httpRequest IsNot Nothing Then
If Not String.IsNullOrEmpty(accept) Then
httpRequest.Accept = accept
End If
If Not String.IsNullOrEmpty(certID) Then
httpRequest.ClientCertificates.Add(m_Certificates(certID))
End If
End If
For Each r As DataRow In headers.Rows
For Each c As DataColumn In headers.Columns
Dim columnName As String = c.ColumnName
Dim val As String = r(columnName).ToString
request.Headers.Add(columnName,val)
Next
Exit For 'Only one row is allowed
Next
If Not String.IsNullOrEmpty(body) Then
Dim requestStream As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(requestStream, New Text.UTF8Encoding(False))
sw.Write(body)
End Using
End If
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
End Using
Screenshots:
Input parameter
Input parameter request token
Request token:
Output parameter:
Blue Prism uses a bit of a peculiar pattern regarding Certificates. The way the Utility - HTTP object is designed is to allow for the loading of certificate files (.cer, etc) on-the-fly into a local Certificate Store, which assigns a new Certificate ID each time.
Before firing your HTTP Request, use the Load Certificate action within the same Utility - HTTP object to output a valid Certificate ID, which you can then pass to HTTP Request's Certificate ID parameter.
I was hoping someone could tell me how to structure a HttpWebRequest in VB.NET to be able to retrieve information using the following API: https://api.developer.lifx.com/docs/list-lights
The code I am interested in replicating is here (in Python):
import requests
token = "YOUR_APP_TOKEN"
headers = {
"Authorization": "Bearer %s" % token,
}
response = requests.get('https://api.lifx.com/v1/lights/all', headers=headers)
A cURL version of this can be seen here:
curl "https://api.lifx.com/v1/lights/all" \
-H "Authorization: Bearer YOUR_APP_TOKEN"
My question is: how do I do this in VB.NET? Would a HttpWebRequest be the way to go? If so, could you please assist me by providing some example code?
I am hoping to retrieve a list of all my lights.
That is correct; A HTTP Request would be the way to go. The python sample code you provided mentions headers which can also be done using a WebHeaderCollection. One other way to do it is using a web client.
Web client (No headers)
Dim client As New WebClient
Dim data As String = client.DownloadString("https://api.lifx.com/v1/lights/all")
With Headers using WebRequest
'String for token
Dim tokenString As String = "YOUR_APP_TOKEN"
'Stream for the responce
Dim responseStream As System.IO.Stream
'Stream reader to read the stream to a string
Dim stringStreamReader As System.IO.StreamReader
'String to be read to
Dim responseString As String
'The webrequest that is querying
Dim webRequest As WebRequest = WebRequest.Create("https://api.lifx.com/v1/lights/all")
'The collection of headers
Dim webHeaderCollection As WebHeaderCollection = webRequest.Headers
'Adding a header
webHeaderCollection.Add("Authorization:Bearer " + tokenString)
'The web responce
Dim webResponce As HttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
'Reading the web responce to a stream
responseStream = webResponce.GetResponseStream()
'Initializing the stream reader with our stream
stringStreamReader = New StreamReader(responseStream)
'Reading the stream to our string
responseString = stringStreamReader.ReadToEnd.ToString
'Ending the web responce
webResponce.Close()
I'm trying to call a WebAPI2 api from a legacy VB code.
The API works when called from fiddler or from the AngularJS client.
[Route("CreateMyObject")]
[HttpPost]
public async Task<JsonResult<MyObject>> CreateMyObject([FromUri] int parentId, [FromBody] MyObject object)
Then in the VB code:
Dim apiUri As New Uri(apiUrl & "api/CreateMyObject?parentId=" &
intParentId.ToString())
Dim data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(myObjectInstance))
Dim webRequest As WebRequest = WebRequest.Create(uri)
webRequest.ContentType = "application/json"
webRequest.Method = "POST"
webRequest.ContentLength = data.Length
Dim stream = webRequest.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()
Dim response = webRequest.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
I can only get a 415 response from the API. I tried other content-types as well, but with the same result or server error.
Whatever is wrong with this call seems to be related with the Json body bit, because if I don't send anything in the call body, the parentId gets to the API as it's supposed to.
As Chase Rocker mentioned, try first by initializing jsonDataBytes as
Dim jsonDataBytes As Bytes()
Also verify the json object to make sure it is fine. Use this link http://jsonlint.com/ or for better assistance use Fiddler
instead.
im currently trying to login to my website, this works however it wont redirect when it logs in. here is my code
Dim request As WebRequest = WebRequest.Create("http://www.jamiehayles.com/test/login.php")
request.Method = "POST"
Dim postData As String = "username=testing&password=lmao1234"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
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()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
RichTextBox1.Text = responseFromServer
reader.Close()
dataStream.Close()
response.Close()
my question is, do i need cookies for it to redirect? and if so any help guys?
Take a look at what you're doing with the response from the server:
Dim responseFromServer As String = reader.ReadToEnd()
RichTextBox1.Text = responseFromServer
All you're doing is reading it and placing the content of the response into a text box. You're not actually responding to a redirect in any way.
A "redirect" means that the server responds with a specific status code and header in the response. The status code tells the browser that the response is an instruction to redirect to another resource. The header contains the new resource that the browser should request.
A web browser checks the response for this code/header and performs a new request. Your code doesn't. It just shows the response to the user, regardless of what it is.
So, to illustrate, a normal redirect happens like this:
Browser: I'm requesting this resource.
Server: Ok, I've received your request, but the resource you really want is actually over there.
Browser: Ok, then I'm now requesting that resource over there.
Server: Ok, here you go.
Your code, however, is more like this:
Code: I'm requesting this resource.
Server: Ok, I've received your request, but the resource you really want is actually over there.
Code: [no further action is taken]
The server instructed your code, in an HTTP-standard way, to request a new resource. Your code simply ignored that instruction.
You need to check the status code of the response, as well as the headers of the response, and make new requests accordingly.
I'm trying to to make a new post through my vb.net application using blogger api.
But I'm fail every time.
Sometimes it's return 403 forbidden error some times Unauthorised error.
Please Help.
Dim mBlogID As String = "5861877551002158183"
Dim AuthToken As String = "AIza......xxxx..........E6g"
Dim post As String = "{""kind"": ""blogger#post"", ""blog"": { ""id"": """ & mBlogID & """}, ""title"": ""abc-title"", ""content"": ""abc-cont""}"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.googleapis.com/blogger/v3/blogs/" & mBlogID & "/posts?key=" & AuthToken), HttpWebRequest)
request.Method = "POST"
request.ContentLength = post.Length
request.ContentType = "application/json"
request.Headers.Add("Authorization: ", AuthToken) '<--- error here
Using requestStream As Stream = request.GetRequestStream()
Dim postBuffer As Byte() = Encoding.ASCII.GetBytes(post)
requestStream.Write(postBuffer, 0, postBuffer.Length)
End Using
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) '<--- Unauthorised error or 403 error here
Using responseStream As Stream = response.GetResponseStream()
Using responseReader As New StreamReader(responseStream)
'Dim json As String = responseReader.ReadToEnd()
'Dim PostURL As String = Regex.Match(json, """url"": ?""(?<id>.+)""").Groups("id").Value
MsgBox(json) 'want to read json response here.
'MsgBox(PostURL)
End Using
End Using
End Using
This code return this error :Specified value has invalid HTTP Header characters.
Parameter name: name
can anybody fix it? I just want to make a new post to blogger and read its URL.
Project Information:-
Platform: Visual Basic 2010
Blogger API Version: V3
I Suggest view this solution. The post has fully explanations.