Visual basic HTTP request - vb.net

Assume, that I wish to use an API from abc.com website.In the api documentation it says,
HTTP/1.x 200 OK
GET /api/now/news
Host: abc.com
Api-Key:xxxxxxxxxx
to get news.
How to write the codes to get a successful response in VB.net
Thank you.

Take https://www.google.com/ for an example, get the source code of the web page in UTF-8 format.
Imports System.Net
Imports System.Text
Public Class Form1
Public Function Getwebcode(ByVal url As String, ByVal encoder As String) As String
Dim myWebClient As WebClient = New WebClient()
Dim myDataBuffer As Byte() = myWebClient.DownloadData(url)
Dim SourceCode As String = Encoding.GetEncoding(encoder).GetString(myDataBuffer)
Return SourceCode
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim back As String = Getwebcode("https://www.google.com/", "UTF-8")
TextBox1.Text = back
End Sub
End Class

Related

vb.net winforms download without blocking

I'm downloading files .mp3 and my goal is not to have even a minimum GUI freezing during downloading.
My aim is also to display the bites received in a progress bar and through labels.
This code is working, but sometimes is freezing without any reason, sometimes the progress bar doesn't work until file is completely done.
So far, this is the "best" code I found online for a completely working progress bar during a download, but still gets problems.
How do you think I can increase performances? How can I make a resistant and reliable working progressbar? How can I download also large file without GUI freezing? I tried (curiosity) to download a 600 mb file and it completely freeze, not responding and not giving any issue back.
Thanks
EDIT1: I'm trying with this,eventhough I'm lost on high waves.. Any idea on how can I use this code and insert it into Jimi Answer? Answer
Imports System.IO
Imports System.IO.Path
Imports System.Net
Public Class Form1
Private downloader As MyDownloader = Nothing
Private Sub btnStartDownload_Click(sender As Object, e As EventArgs) Handles btnStartDownload.Click
Dim progress = New Progress(Of String)(
Sub(data)
MsgBox("we are on the UI thread here")
End Sub)
Dim url As Uri = New Uri(TextBox1.Text)
downloader = New MyDownloader()
'How can I remove this second? I don't need download from url every 1 second.
downloader.StartDownload(progress, url, 1)
End Sub
And
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Net
Imports System.Net.Http
Imports System.Text.RegularExpressions
Imports System.Threading
Public Class MyDownloader
Private Shared ReadOnly client As New HttpClient()
client.DownloadProgressChanged += AddressOf Client_DownloadProgressChanged
client.DownloadFileCompleted += AddressOf Client_DownloadFileCompleted
Private interval As Integer = 0
Private Sub Client_DownloadFileCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
System.Windows.Forms.MessageBox.Show("Download OK!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Public Sub StartDownload(progress As IProgress(Of String), url As Uri, intervalSeconds As Integer)
interval = intervalSeconds * 1000
Task.Run(Function() DownloadAsync(progress, url))
End Sub
Private Sub Client_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
ProgressBar1.Minimum = 0
Dim receive As Double = Double.Parse(e.BytesReceived.ToString())
Dim total As Double = Double.Parse(e.TotalBytesToReceive.ToString())
Dim percentage As Double = receive / total * 100
label2.Text = $"{String.Format("{0:0.##}", percentage)}%"
ProgressBar1.Value = Integer.Parse(Math.Truncate(percentage).ToString())
End Sub
Private Async Function DownloadAsync(progress As IProgress(Of String), url As Uri) As Task
Dim pattern As String = "<(?:[^>=]|='[^']*'|=""[^""]*""|=[^'""][^\s>]*)*>"
Dim downloadTimeWatch As Stopwatch = New Stopwatch()
downloadTimeWatch.Start()
Do
Try
Dim response = Await client.GetAsync(url, HttpCompletionOption.ResponseContentRead)
Dim data = Await response.Content.ReadAsStringAsync()
data = WebUtility.HtmlDecode(Regex.Replace(data, pattern, ""))
progress.Report(data)
Dim delay = interval - CInt(downloadTimeWatch.ElapsedMilliseconds)
Await Task.Delay(If(delay <= 0, 10, delay))
downloadTimeWatch.Restart()
Catch ex As Exception
End Try
Loop
End Function
End Class
I'm Seriously lost on it, I tried to delete cancel download as I am not going to stop any download and I tried also to delete Download from url every 1 second as I just need one time download for every link.
Thanks

Trying to write IP address to textbox in Visual Basic

I am trying to write a simple program that finds the public IP for the computer it is being used on. However, I am not sure how to set the text of the TextBox to the IP address that is found. Can anyone help me?
Code:
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
Private Function GetMyIP() As IPAddress
Using wc As New WebClient
Return IPAddress.Parse(Encoding.ASCII.GetString(wc.DownloadData("http://tools.feron.it/php/ip.php")))
End Using
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = (GetMyIP())
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
End Class
First, you should use Option Strict On. That would point out to you that you need to use
TextBox1.Text = GetMyIP().ToString()
Next, if you examine the headers from that web page you will see it returns the result in UTF-8 encoding, so you should use Encoding.UTF8 instead of Encoding.ASCII. Unfortunately, that still does not work - I will write more on that later.
However, WebClient has a DownloadString method which works well in this case:
Private Function GetMyIP() As IPAddress
Using wc As New WebClient
Dim url = "http://tools.feron.it/php/ip.php"
Dim x = wc.DownloadString(url)
Return IPAddress.Parse(x.Trim())
End Using
End Function
If you still want to use DownloadData, you should examine the returned bytes: you would find that the data you want is preceded by the bytes 0xEF 0xBB 0xBF. I do not know why. This is messing up the string that you want if you download it as an array of bytes.
You could use LINQ to remove the strange bytes:
Private Function GetMyIP() As IPAddress
Using wc As New WebClient
Dim url = "http://tools.feron.it/php/ip.php"
Dim x = wc.DownloadData(url)
Dim y = Encoding.UTF8.GetString(x.Where(Function(b) b < 128).ToArray())
Return IPAddress.Parse(y)
End Using
End Function
(I could have used Encoding.ASCII in there because the bytes over 127 have been removed.)

Visual Basic - Web Request 403 Forbidden

I am new to Visual Basic so I dont know much about Syntax e.t.c
So if anyone could help me out that be great!
Im getting a 403 Forbidden Error most likely because of the User Agent being used. The website is probably picking up that its not an actual user entering the Website and therefore blocks access.
How do I apply a User Agent that will bypass this issue? I have no idea where to put the Syntax.
My Code:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sources(1) As String
array(0) = "http://proxy-ip-list.com"
array(1) = "http://sslproxies24.blogspot.com/feeds/posts/default"
For Each element As String In sources
'Connect to the Proxy Source;
Dim source As Net.HttpWebRequest = Net.WebRequest.Create(element)
'Prepare the Response;
Dim response As Net.HttpWebResponse = source.GetResponse
'Load the HTML;
Dim reader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Dim html As String = reader.ReadToEnd
'Regex;
Dim expression As New Regex("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,4}")
'Set the Matches variable to the Matched Sections of the HTML source;
Dim matches As MatchCollection = expression.Matches(html)
'Add the proxies to the ListBox;
For Each proxy As Match In matches
ListBox1.Items.Add(proxy)
Next
Next
End Sub
End Class

Super slow HttpWebRequest

I'm making a website scraper for a project I'm doing. I've gotten everything to work great, however, loading the actual page takes F-O-R-E-V-E-R. You can see the page it's loading here:
MCServerList.Net
Here is the code I am using:
private CONST REQUESTURL as string = "http://www.MCServerList.net/?page="
private chunkId as int32 = 1
Dim req As HttpWebRequest = WebRequest.Create(REQUESTURL & chunkId)
Dim res As HttpWebResponse = req.GetResponse()
Dim Stream As Stream = res.GetResponseStream()
I then use "Stream" and load it through the HTMLAgilityPack found free online. It loads the page quickly, however, the initial request usually takes ~20-30 seconds.
Any help would be appreciated!
I just ran the following code and ignoring the first initial compile I average about 3.3 seconds for GetResponse() and 0.2 more seconds for Load(). Are you on a fast connection? Are you sure this is where the bottleneck is?
Option Explicit On
Option Strict On
Imports System.Net
Public Class Form1
Private Const REQUESTURL As String = "http://www.MCServerList.net/?page="
Private chunkId As Int32 = 1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ST As New System.Diagnostics.Stopwatch()
ST.Start()
Dim req = WebRequest.Create(REQUESTURL & chunkId)
Dim res = req.GetResponse()
Trace.WriteLine(String.Format("GetResponse() : {0}", ST.Elapsed))
Using Stream As System.IO.Stream = res.GetResponseStream()
Dim X As New HtmlAgilityPack.HtmlDocument()
X.Load(Stream)
End Using
Trace.WriteLine(String.Format("Load() : {0}", ST.Elapsed))
ST.Stop()
End Sub
End Class

paypal API in VB.net

Hey all, i have converted some C# PayPal API Code over to VB.net. I have added that code to a class within my project but i can not seem to access it:
Imports System
Imports com.paypal.sdk.services
Imports com.paypal.sdk.profiles
Imports com.paypal.sdk.util
Namespace GenerateCodeNVP
Public Class GetTransactionDetails
Public Sub New()
End Sub
Public Function GetTransactionDetailsCode(ByVal transactionID As String) As String
Dim caller As New NVPCallerServices()
Dim profile As IAPIProfile = ProfileFactory.createSignatureAPIProfile()
profile.APIUsername = "xxx"
profile.APIPassword = "xxx"
profile.APISignature = "xxx"
profile.Environment = "sandbox"
caller.APIProfile = profile
Dim encoder As New NVPCodec()
encoder("VERSION") = "51.0"
encoder("METHOD") = "GetTransactionDetails"
encoder("TRANSACTIONID") = transactionID
Dim pStrrequestforNvp As String = encoder.Encode()
Dim pStresponsenvp As String = caller.[Call](pStrrequestforNvp)
Dim decoder As New NVPCodec()
decoder.Decode(pStresponsenvp)
Return decoder("ACK")
End Function
End Class
End Namespace
I am using this to access that class:
Private Sub cmdGetTransDetail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetTransDetail.Click
Dim thereturn As String
thereturn =GetTransactionDetailsCode("test51322")
End Sub
But it keeps telling me:
Error 2 Name 'GetTransactionDetailsCode' is not declared.
I'm new at calling classes in VB.net so any help would be great! :o)
David
Solved
Dim payPalAPI As New GenerateCodeNVP.GetTransactionDetails
Dim theReturn As String
theReturn = payPalAPI.GetTransactionDetailsCode("test51322")
You're probably getting that error because you need to call it like this:
Private Sub cmdGetTransDetail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetTransDetail.Click
Dim thereturn As String
Dim myTransaction as new GetTransactionDetails
thereturn = myTransaction.GetTransactionDetailsCode("test51322")
End Sub
Or you can make the function be a public shared function and access it as if it were a static method
Your GetTransactionDetailsCode method is an instance method of the GetTransactionDetails class, which means that you need an instance of the GetTransactionDetails class in order to call the method.
You can do that like this:
Dim instance As New GetTransactionDetails()
thereturn = instance.GetTransactionDetailsCode("test51322")
However, your method doesn't actually use the class instance, so you should change your GetTransactionDetails class to a Module instead.