環境
VB.net
(VisualStudio2019 .net Framework 4.8)
HttpClientを使用して、Httpアクセスをしようと思い、以下のページにあったサンプルを作成してみたのですが、動作しません。
コンソールアプリとして実行したときは動作するのですが、同じコードをフォームに張り付け、ボタン押下で実効しようとすると、response = Await clinet.GetAsync(url)の行で固まり応答がありません。
フォーム上より動作させるときは何かサンプルに手を加える必要があるのでしょうか。
コンソールアプリ
VB
1 Sub Main(args As String()) 2 Dim urls As String() = {"https://just4fun.biz/me.html", "https://windev.just4fun.biz/me.html"} 3 Dim client As HttpClient = New HttpClient() 4 5 For Each url As String In urls 6 Dim content As String = (HtmlContent(url, client)).Result 7 Console.WriteLine("URL:{0}, Content:{1}", url, content) 8 Next 9 End Sub 10 11 Private Async Function HtmlContent(ByVal url As String, ByVal clinet As HttpClient) As Task(Of String) 12 Dim response As HttpResponseMessage = Nothing 13 Console.WriteLine("Connect {0}...", url) 14 15 Try 16 response = Await clinet.GetAsync(url) 17 response.EnsureSuccessStatusCode() 18 Dim responseBody As String = Await response.Content.ReadAsStringAsync() 19 Return Await response.Content.ReadAsStringAsync() 20 Catch ex As Exception 21 Console.WriteLine("Exception Message :{0} ", ex.Message) 22 End Try 23 24 Return Nothing 25 End Function
フォーム
VB
1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 2 Dim urls As String() = {"https://just4fun.biz/me.html", "https://windev.just4fun.biz/me.html"} 3 Dim client As HttpClient = New HttpClient() 4 5 For Each url As String In urls 6 Dim content As String = (HtmlContent(url, client)).Result 7 Console.WriteLine("URL:{0}, Content:{1}", url, content) 8 Next 9 10 End Sub 11 Private Async Function HtmlContent(ByVal url As String, ByVal clinet As HttpClient) As Task(Of String) 12 Dim response As HttpResponseMessage = Nothing 13 Console.WriteLine("Connect {0}...", url) 14 15 Try 16 response = Await clinet.GetAsync(url) 17 response.EnsureSuccessStatusCode() 18 Dim responseBody As String = Await response.Content.ReadAsStringAsync() 19 Return Await response.Content.ReadAsStringAsync() 20 Catch ex As Exception 21 Console.WriteLine("Exception Message :{0} ", ex.Message) 22 End Try 23 24 Return Nothing 25 End Function
回答2件
あなたの回答
tips
プレビュー