How to parse Net.WebClient results with VB.net - vb.net

Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
'reqparm.Add("param1", "somevalue")
'reqparm.Add("param2", "othervalue")
Dim responsebytes = client.UploadValues("http://ip2country.sourceforge.net/ip2c.php?format=JSON", "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using
Results in:
{ip: "184.23.135.130",hostname:
"184-23-135-130.dedicated.static.sonic.net",country_code:
"US",country_name: "United States"}
Looking for any help

I figured it out. I included Json.net references.
Imports Newtonsoft.Json.Linq
Imports System.Net
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
'reqparm.Add("param1", "somevalue")
'reqparm.Add("param2", "othervalue")
Dim responsebytes = client.UploadValues("http://ip2country.sourceforge.net/ip2c.php?format=JSON", "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
Dim blah As String = client.DownloadString("http://ip2country.sourceforge.net/ip2c.php?format=JSON")
Dim json As JObject = JObject.Parse(responsebody)
Console.WriteLine(json.SelectToken("ip"))
Console.WriteLine(json.SelectToken("hostname"))
Console.WriteLine(json.SelectToken("country_code"))
Console.WriteLine(json.SelectToken("country_name"))
Console.ReadKey()
End Using

Related

GetResponse not a member of WebRequest in UWP

I wrote a VB program to access information from the Web.
It works but when trying to do the same thing in UWP (Universal Windows) …
I get the following message:
"'GetResponse' is not a member of 'WebRequest'"
Here is the code I am using less the website info. How can this code be used in the Universal Windows Platform.
Imports System
Imports System.IO
Imports System.Net
Module Code
Sub SendWebRequest()
Dim MyWebRequest As WebRequest
Dim MyWebResponse As WebResponse
Dim SR As StreamReader
Dim ReadString As String
Dim MyCache As New CredentialCache()
Dim MyCredential As NetworkCredential = MyCache.GetCredential(New Uri("http://xxxxxx.com:xxxx"), "Basic")
If MyCredential Is Nothing Then
MyCache.Add(New Uri("http://http://xxxxxx.com:xxxx"), "Basic", New NetworkCredential("UserName", "UsePassWord"))
End If
MyWebRequest = WebRequest.Create("http://http://xxxxxx.com:xxxx/xxxx")
MyWebRequest.Credentials = myCache
MyWebResponse = MyWebRequest.GetResponse()
SR = New StreamReader(MyWebResponse.GetResponseStream)
Do
ReadString = SR.ReadLine
If InStr(ReadString, "Listen to the pronunciation of") Then
'Do Something
Exit Do
End If
Loop Until SR.EndOfStream
MyWebResponse.Close()
End Sub
End Module
I updated using adding Async and Await . . .
Run time issue at MyWebresponse = Await MyWebRequest.GetResponseAsync()
Exception User-Unandled: System.PlatformNotSupportedException: 'The value 'System.Net.CredentialCache' is not supported for property 'Credentials'.'
Async Sub SendWebRequest()
Dim MyWebRequest As WebRequest
Dim MyWebResponse As WebResponse
Dim SR As StreamReader
Dim ReadString As String
Dim MyCache As New CredentialCache()
Dim MyCredential As NetworkCredential = MyCache.GetCredential(New Uri("http://xxxxxx.com:xxxx"), "Basic")
If MyCredential Is Nothing Then
MyCache.Add(New Uri("http://http://xxxxxx.com:xxxx"), "Basic", New NetworkCredential("UserName", "UsePassWord"))
End If
MyWebRequest = WebRequest.Create("http://http://xxxxxx.org:xxxx/xxxx")
MyWebRequest.Credentials = myCache
MyWebResponse = Await MyWebRequest.GetResponseAsync()
SR = New StreamReader(MyWebResponse.GetResponseStream)
Do
ReadString = SR.ReadLine
If InStr(ReadString, "Listen to the pronunciation of") Then
'Do Something
Exit Do
End If
Loop Until SR.EndOfStream
MyWebResponse.Close()
End Sub
If someone can see what I am doing wrong above, I'd appreciate it.
In the mean time I'll try HttpClient as suggested by jmcilhinney
In theory, you should be able to change this:
Sub SendWebRequest()
to this
Async Sub SendWebRequest()
and this:
MyWebResponse = MyWebRequest.GetResponse()
to this:
MyWebResponse = Await MyWebRequest.GetResponseAsync()
This thread indicates that that might not work though. It does suggest an HttpClient as an alternative though, which would mean code something like this:
Dim client As New HttpClient
Dim response = Await client.GetAsync(New Uri("URL here"))
If response.IsSuccessStatusCode Then
Dim data = Await response.Content.ReadAsStringAsync()
For Each line In data.Split({vbLf, vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
'Use line here.
Next
End If
Note that I'm not 100% sure whether those 'vb' constants would work in UWP but I used them here for simplicity.
The following does what I need in UWP. Send a Web Request and monitor the return.
...Thanks jmcilhinney for your help
Imports System.Net
Imports System.Net.Http
Imports System.Text
Module Code
Async Sub SendWebRequest()
Dim client As New HttpClient
Dim byteArray = Encoding.ASCII.GetBytes("UserName:PassWord")
client.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray))
Dim response = Await client.GetAsync(New Uri("http://xxxxx.xxxxxx.org:####/xxxxx"))
If response.IsSuccessStatusCode Then
Dim data = Await response.Content.ReadAsStringAsync()
For Each line In data.Split({vbLf, vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
'Use line here.
Next
End If
End Sub
End Module

The given credentials or configuration format does not fits to the storage provider (Sharpbox)

I am new to cloud storage, I encountered this error
The given credentials or configuration format does not fits to the storage provider
when I tried to read a txt file with token (uploadMe sub). I am using vb. Looking forward to your reply.
My code:
Dim ConsumerKey As String = "******************"
Dim ConsumerSecret As String = "*****************"
Dim config As DropBoxConfiguration = DropBoxConfiguration.GetStandardConfiguration()
Dim requestToken As DropBoxRequestToken
Private Sub AuthorizeMe()
config.AuthorizationCallBack = New Uri("http://www.google.com")
requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, ConsumerKey, ConsumerSecret)
Dim AuthorizationUrl As String = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken)
Process.Start(AuthorizationUrl)
End Sub
Private Sub saveMyAuth()
Dim accessToken As ICloudStorageAccessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config, ConsumerKey, ConsumerSecret, requestToken)
Dim DropboxStorage As New CloudStorage()
DropboxStorage.Open(config, accessToken)
Dim File As FileStream = New FileStream("c:\TEMP\MyToken.txt", FileMode.Create, System.IO.FileAccess.Write)
DropboxStorage.SerializeSecurityTokenToStream(requestToken, File)
File.Close()
End Sub
Private Sub uploadme()
Try
Dim configio As DropBoxConfiguration = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
Dim DropboxStorage As New CloudStorage()
Dim accessToken As ICloudStorageAccessToken
Using fs = File.Open("C:\TEMP\MyToken.txt", FileMode.Open, FileAccess.Read, FileShare.None)
accessToken = DropboxStorage.DeserializeSecurityToken(fs)
End Using
DropboxStorage.Open(configio, accessToken)
Dim srcFile = Environment.ExpandEnvironmentVariables("C:\TEMP\mysqlbackup.xml")
DropboxStorage.UploadFile(srcFile, "/")
DropboxStorage.Close()
Catch ex As Exception
Console.Beep()
Console.Write(ex.Message, "")
End Try
End Sub

REST WebService: how to get zip file from web service to a client

I'm trying to create a function to download a zip file made ​​available from a REST WebService with a client that calls the Web Service(both written in VB.Net).
WebService side I have the following code:
Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
Dim length As Integer = CType(f.Length, Integer)
WebOperationContext.Current.OutgoingResponse.ContentLength = length
Dim buffer As Byte() = New Byte(length) {}
Dim sum As Integer = 0
Dim count As Integer
While ((count = f.Read(buffer, sum, length - sum)) > 0)
sum += count
End While
f.Close()
Dim mimeType = ""
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
Return New MemoryStream(buffer)
End Function
Client side I have the following code:
sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False
Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Response has ContentLenght = 242699, so seems to receive the stream, but StIn seems to be empty. What is the best solution to solve the problem?
I think you've forgot to read from the StreamReader to the file.
Dim inSaveFile As String = "C:\stream\test.doc"
If Dir(inSaveFile) <> vbNullString Then
Kill(inSaveFile)
End If
Dim swFile As System.IO.StreamWriter
Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)
Dim response1 As System.Net.HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)
swFile.WriteLine(stIn.ReadToEnd)
swFile.Close()
fs.Close()

How to get my real IP using vb.net?

How to get my real IP using vb.net?
If you are running in ASP.NET, then use the HttpRequest.UserHostAddress property:
Dim ip as string
ip = Request.UserHostAddress()
Create php script. Save it as realip.php
<?php
echo $this->getRealIpAddr();
function getRealIpAddr()
{
$ip = "";
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
?>
In your VB.net project create a module.
Declare the imports section at the very top
Imports System.Net
Imports System.IO
And create your function:
Public Function GetIP() As String
Dim uri_val As New Uri("http://yourdomain.com/realip.php")
Dim request As HttpWebRequest = HttpWebRequest.Create(uri_val)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim myIP As String = reader.ReadToEnd()
response.Close()
Return myIP
End Function
Now anywhere in your code you can issue
Dim myIP as String = GetIP()
as use the value from there as you wish.
As you can see here (how and why), the best way to get the client IP is:
Dim clientIP As String
Dim ip As String = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If Not String.IsNullOrEmpty(ip) Then
Dim ipRange As String() = ip.Trim().Split(","C)
Dim le As Integer = ipRange.Length - 1
clientIP = ipRange(le)
Else
clientIP = Request.ServerVariables("REMOTE_ADDR")
End If
Dim req As HttpWebRequest = WebRequest.Create("http://whatismyip.com/automation/n09230945.asp")
Dim res As HttpWebResponse = req.GetResponse()
Dim Stream As Stream = res.GetResponseStream()
Dim sr As StreamReader = New StreamReader(Stream)
MsgBox(sr.ReadToEnd())

How to post XML document to HTTP with VB.Net

I'm looking for help with posting my XML document to a url in VB.NET. Here's what I have so far ...
Public Shared xml As New System.Xml.XmlDocument()
Public Shared Sub Main()
Dim root As XmlElement
root = xml.CreateElement("root")
xml.AppendChild(root)
Dim username As XmlElement
username = xml.CreateElement("username")
username.InnerText = _username
root.AppendChild(username)
xml.Save(Console.Out)
Dim url = "https://mydomain.com"
Dim req As WebRequest = WebRequest.Create(url)
req.Method = "POST"
req.ContentType = "application/xml"
req.Headers.Add("Custom: API_Method")
Console.WriteLine(req.Headers.ToString())
This is where things go awry:
I want to post the xml, and then print the results to console.
Dim newStream As Stream = req.GetRequestStream()
xml.Save(newStream)
Dim response As WebResponse = req.GetResponse()
Console.WriteLine(response.ToString())
End Sub
This is essentially what I was after:
xml.Save(req.GetRequestStream())
If you don't want to take care about the length, it is also possible to use the WebClient.UploadData method.
I adapted your snippet slightly in this way.
Imports System.Xml
Imports System.Net
Imports System.IO
Public Module Module1
Public xml As New System.Xml.XmlDocument()
Public Sub Main()
Dim root As XmlElement
root = xml.CreateElement("root")
xml.AppendChild(root)
Dim username As XmlElement
username = xml.CreateElement("username")
username.InnerText = "user1"
root.AppendChild(username)
Dim url = "http://mydomain.com"
Dim client As New WebClient
client.Headers.Add("Content-Type", "application/xml")
client.Headers.Add("Custom: API_Method")
Dim sentXml As Byte() = System.Text.Encoding.ASCII.GetBytes(xml.OuterXml)
Dim response As Byte() = client.UploadData(url, "POST", sentXml)
Console.WriteLine(response.ToString())
End Sub
End Module