I have a little problem when using HttpClient. I plan to make several web requests, mainly GET and POST. A few years ago I was able to do it without worries, and there I wanted to do a little project again, only it doesn't work anymore: the program freezes (because it's not asynchronous but I don't really care for that) and sends me a timeout. There I'm using HttpClient, which is safer than HttpWebRequest from what I understand, because before that's what I was using. So code problem or other, I don't really know.. I tried with several hosts but all the time the same. There the test is carried out with youtube. It must show me the answer, so the source code of the page logically.
Here is the code used:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(WRequest("https://www.youtube.com/", "GET", ""))
'WRequest("http://", "POST", "name=jane&stat=active")
End Sub
Function WRequest(URL As String, method As String, POSTdata As String) As String
Dim responseData As String = ""
Try
Dim cookieJar As New Net.CookieContainer()
Dim hwrequest As Net.HttpWebRequest = Net.WebRequest.Create(URL)
hwrequest.CookieContainer = cookieJar
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 600
hwrequest.Method = method
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader =
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function
End Class
hwrequest.Timeout = 600, quite inappropriate. The default is100,000-- not asynchronous but I don't really care: you doOption StricttoON. You care about that, too