vb.net OpenWeatherMap using HttpWebRequest - vb.net

I am unable to get the HttpWebRequest to work properly with OpenWeatherMap.
When I try out the URL from the browser I get the data. However, when I am sending it from the program I'm getting a message with code id. Like this:
"message":"","cod":"404"
What Am I doing wrong?
VB.NET Code:
Private Shared AppID As String = "add_app_id_Here"
Public Shared Function GetWeather(ByVal location As String) As List(Of WeatherDetails)
Dim url = String.Format _
("http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&type=accurate&mode=xml&units=metric&cnt=3&appid={1}",
location, AppID)
Try
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
request.AuthenticationLevel = Net.Security.AuthenticationLevel.None
Dim response As WebResponse = request.GetResponse()
'The body of the request is sent here
Dim responseReader As New StreamReader(response.GetResponseStream())
Dim responseInfo As String = responseReader.ReadToEnd()
responseReader.Close()
response.Close()
If Not (responseInfo.Contains("message") And responseInfo.Contains("cod")) Then
Dim xEl = XElement.Load(New System.IO.StringReader(responseInfo))
Return GetWeatherInfo(xEl)
Else
Return New List(Of WeatherDetails)
End If
Catch ex As Exception
Return New List(Of WeatherDetails)
End Try
End Function

After breaking my head I found that his method HttpWebRequest is not tolerant to special characters or non printable characters.
Thus in the URL I had to hardcode the "%27" character and it solved the problem.

Related

How do I add grant_type, username and password to API request in VB.net

I'm trying to figure out how to get an authorization token from the BIC - BOXTECH API. I can do it in a program called POSTMAN that helps with API stuff, but I cannot work out how to take what I have in POSTMAN and code it into my VB.NET application. I believe I may need to add a BODY to my HTTPWebRequest but don't know how. Can anyone point me in the right direction. New to API's. Thx.
This is the code I have so far - but missing the way to add:
grant_type=password
username=myemail#somedomain.com
password=mypassword
Public Function GetBoxAPIToken() As String
Try
Dim request As WebRequest = HttpWebRequest.Create($"https://app.bic-boxtech.org/oauth/token")
With request
.Headers.Add("Authorization", $"Basic YmljYXBwOmJpY3NlY3JldGFwcA==")
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
End With
Using response As WebResponse = request.GetResponse()
Using streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim jsonResponseText As String = streamReader.ReadToEnd()
Dim m As JArray = JArray.Parse(jsonResponseText)
Console.WriteLine(m.Item(0).Item("accessToken"))
Return m.Item(0).Item("accessToken")
End Using
End Using
Catch ex As Exception
'Catch error here...
Return Nothing
End Try
End Function

Send a POST request with vb.net gives 400 bad request error

I am not familiar a lot with Vb.Net, but I try to tweak something on an existent project. I have a cURL that try to implement on Vb.Net. I found different answers here and in other forums, but this way is the one I managed to reach
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New IO.StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Dim postData As String = String.Format("text={0}", title)
Dim data = Encoding.UTF8.GetBytes(postData)
Dim uri = New Uri("https://.....")
Dim slackResponse = SendRequest(uri, data, "application/json", "POST")
And this is the error I get:
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.
If I comment out the SendRequest function, I got an error during calling that, so I guess it is on that part.
Not able to debug more. Any ideas?
In order to debug more, you need to catch the WebException. WebExceptions have a response object that may contain more information.
Dim response as WebResponse
Try
response = req.GetResponse().GetResponseStream()
Catch ex As Net.WebException
If ex.Response IsNot Nothing Then
response = ex.Response
End If
End Try
This could be a problem with your URL parameters but many sites also return this class of error when there is a problem in the json content of the request.
I solved this long time ago by adding.
request.ContentType = "application/x-www-form-urlencoded"

Taking Json from API and iterating over the results

So I feel stupid for asking probably a easy question but I'm not very familiar with .NET and I've been googling for a while now.
I'm looking to take in data from a web API and be able to iterate over it. The data looks like this
[
{"id":"5", "date":"01-01-2014"},
{"id":"90", "date":"05-01-2013"}
]
What I've got so far:
Private Sub newGetData()
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://somesite.com"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList
For Each item As JProperty In results
item.CreateReader()
MsgBox(item.name)
Next
'usernameTextbox.text = jResults("name").ToString()
'placenameTextbox.text = jResults("place")("name").ToString()
Catch ex As Exception
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
End Sub
I've tried a bunch of things but it always fails on the loop. How do I go about doing this?
EDIT: The error message for this one
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader)
at Newtonsoft.Json.Linq.JObject.Parse(String json)
at Forecasting.Form1.newGetData() in

How do I read text directly from a URL using VB.net?

I'm making a Windows Phone 8 app. I have the latitude and longitude of the target location. I need to get the Two Letter ISO country code of target location.
I'm using the following code to make it happen.
'Dim address As String = puri
'Dim client As WebClient = New WebClient()
'Dim reader As StreamReader = New StreamReader(address)
'code = reader.ReadToEnd
Dim inStream As StreamReader
Dim wr As WebRequest
Dim webresponse As WebResponse
wr = WebRequest.Create(puri)
webresponse = wr.GetResponse()
inStream = New StreamReader(webresponse.GetResponseStream())
code = inStream.ReadToEnd()
where puri(in the commented code) is the address of the webservice in string format.
When trying the commented code, the error I'm getting is that string cannot be converted to system.uri format. (address)
When trying the uncommented code, I get an error which says, getresponse is not a member of class system.net.webrequest()
I guess with the updates to .NET the code changed, but I couldn't find anything current on the topic.
URI = http://api.geonames.org/countryCode?lat=17.60890&lng=76.98966&username=demo
I think you should use WebClient Class instead of a WebRequest. It is simpler and faster. Here is a simple example:
Dim WebCL As New WebClient
Dim DownLoadedText As String = String.Empty
Try
DownLoadedText = WebCL.DownloadString("Your Url")
' Do something
Catch ex As Exception
Throw New Exception("Oops!! ERROR has occured, something is wrong with your address")
End Try

Is there any way to optimize performance of reading stream?

I'm requesting remote SOAP web-service but all operation (from click search button to render interface with answer) took almost two minutes, it's too long. So I wonder if there any possible way to improve performance of the current code.
Operation that parse xml and read data to database working quite well, problem only about reading answer from stream.
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using rd As New StreamReader(bs)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Function
Here is solution!
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate")
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using gz As New GZipStream(bs, CompressionMode.Decompress)
Using rd As New StreamReader(gz)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Using
End Function