Visual Basic サンプル集 |
Visual Basic 中学校 > Visual Basic サンプル集 > Visual Basic サンプル集目次 >
REST WebAPIを呼び出す
2021/1/10
目次
GET のWebAPIを呼び出す
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons/Shakespeare" Using client As New System.Net.Http.HttpClient() Using response As System.Net.Http.HttpResponseMessage = client.GetAsync(url).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して Shakespeare(シェークスピア)の情報を取得します。 → 人物情報のWebAPIについてはこちら
実行するとこのように出力されます。
{"success":true,"data":{"name":"Shakespeare","note":"Hamlet","age":13,"registerDate":"1564-04-26T20:21:00"}} |
GET のWebAPIを呼び出してJSONの戻り値を解析する
この例では、WebAPIを呼び出して、レスポンスとして取得した戻り値のJSONを解析して、そこに含まれる name・note・age・registerDateの各値を抜き出します。
この例を実行するには、NuGet で NewtonSoft.JSON をインストールする必要があります。 → その方法
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons/Shakespeare" Using client As New System.Net.Http.HttpClient() Using response As System.Net.Http.HttpResponseMessage = client.GetAsync(url).Result '生のレスポンス全体を文字列で取得 Dim responseBody As String = response.Content.ReadAsStringAsync().Result 'レスポンスの文字列をJSONとして解析されたJObjectに変換。 Dim oResponse As Newtonsoft.Json.Linq.JObject = CType(Newtonsoft.Json.JsonConvert.DeserializeObject(responseBody), Newtonsoft.Json.Linq.JObject) 'レスポンスに含まれる各値を取得。 Dim success As Boolean = oResponse("success").ToObject(Of Boolean) Dim dataName As String = oResponse("data")("name").ToString Dim dataNote As String = oResponse("data")("note").ToString Dim dataAge As Integer = oResponse("data")("age").ToObject(Of Integer) Dim dataRegisterDate As Date = oResponse("data")("registerDate").ToObject(Of Date) '各値を出力 Debug.WriteLine($"呼び出し成功 = {success}") Debug.WriteLine($"名前 = {dataName}") Debug.WriteLine($"備考 = {dataNote}") Debug.WriteLine($"年齢 = {dataAge}") Debug.WriteLine($"登録日時 = {dataRegisterDate}") End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して Shakespeare(シェークスピア)の情報を取得します。 → 人物情報のWebAPIについてはこちら
POST のWebAPIを本文を設定して呼び出す
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons" Using client As New Net.Http.HttpClient() Dim jsonText As String = "{""name"":""卑弥呼"",""note"":""邪馬台国"",""age"":75,""registerDate"":""0204-01-01T02:03:04""}" Dim requestContent As New Net.Http.StringContent(jsonText, System.Text.Encoding.UTF8, "application/json") Using response As Net.Http.HttpResponseMessage = client.PostAsync(url, requestContent).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して 卑弥呼(ひみこ) を登録します。人物情報のWebAPIでは、POSTの本文にJSON形式で人物情報を設定することで新しい人物を登録できます。 → 人物情報のWebAPIについてはこちら
メモ:人物情報のWebAPIではブラウザーに下記URLを入力すると、登録されている全人物が表示されます。これを使って正しく登録されているか確認できます。
https://umayadia-apisample.azurewebsites.net/api/persons
メモ:人物情報のWebAPIでは、レスポンスの success が false の場合処理に失敗しています。この場合、レスポンスの errorMessage で失敗した原因がわかることがあります。このサンプルでは Debug.WriteLine でレスポンスを出力しています。
下記は、人物情報のWebAPIでのエラーレスポンスの例です。
{"success":false,"errorCode":"AE101","errorMessage":"nameの文字数が多すぎます。20文字以内にしてください。"} |
PUT のWebAPIを本文を設定して呼び出す
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons/平賀源内" Using client As New Net.Http.HttpClient() Dim jsonText As String = "{""name"":""平賀源内"",""note"":""エレキテル"",""age"":26,""registerDate"":""1728-01-01T00:00:00""}" Dim requestContent As New Net.Http.StringContent(jsonText, System.Text.Encoding.UTF8, "application/json") Using response As Net.Http.HttpResponseMessage = client.PutAsync(url, requestContent).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して 平賀源内 の情報を更新します。デフォルトでは年齢が24歳なのを26歳にします。人物情報のWebAPIでは、PUTの本文にJSON形式で人物情報を設定することで、URLで指定した人物の情報を更新できます。→ 人物情報のWebAPIについてはこちら
メモ:誰かが平賀源内を削除していた場合、この処理は失敗します。
メモ:人物情報のWebAPIではブラウザーに下記URLを入力すると、登録されている全人物が表示されます。これを使って正しく登録されているか確認できます。
https://umayadia-apisample.azurewebsites.net/api/persons
メモ:人物情報のWebAPIでは、レスポンスの success が false の場合処理に失敗しています。この場合、レスポンスの errorMessage で失敗した原因がわかることがあります。このサンプルでは Debug.WriteLine でレスポンスを出力しています。
下記は、人物情報のWebAPIでのエラーレスポンスの例です。
{"success":false,"errorCode":"AE101","errorMessage":"nameの文字数が多すぎます。20文字以内にしてください。"} |
DELETE のWebAPIを呼び出す
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons/彦坐王" Using client As New System.Net.Http.HttpClient() Using response As System.Net.Http.HttpResponseMessage = client.DeleteAsync(url).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して 彦坐王(ひこいますのおう。実在すれば2世紀か3世紀頃の人物)を削除します。→ 人物情報のWebAPIについてはこちら
メモ:彦坐王が登録されていない場合、次のエラーレスポンスを出力します。
{"success":false,"errorCode":"DE101","errorMessage":"彦坐王は存在しないため削除できません。"} |
OPTIONS のWebAPIを呼び出す
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons" Using client As New System.Net.Http.HttpClient() Dim request As New Net.Http.HttpRequestMessage(Net.Http.HttpMethod.Options, url) Using response As System.Net.Http.HttpResponseMessage = client.SendAsync(request).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して persons リソースに対して有効なメソッドの一覧を取得します。→ 人物情報のWebAPIについてはこちら
実行するとこのように出力されます。
{"success":true,"data":["GET api/<PersonsController> :すべての人物の一覧を取得します。","GET api/<PersonsController>/{name} :{name}で指定された人物を取得します。","POST api/<PersonsController> :人物を追加します。ボディにJSON形式で人物を指定します。","PUT api/<PersonsController>/{name} :{name}で指定された人物を変更します。ボディにJSON形式で変更後の人物の値を指定します。","DELETE api/<PersonsController>/{name} :{name}で指定された人物を削除します。","DELETE api/<PersonsController>/all/reset :すべての人物を初期状態に戻します。すべての変更は失われます。","OPTIONS api/<PersonsController> :personsに対して有効なメソッドの一覧を取得します。"]} |
認証が必要なプロキシーを経由して WebAPIを呼び出す
認証が必要なプロキシーを使用している環境では、次のようにプロキシーの情報を設定します。
※私はプロキシー環境下でこのプログラムの動作を確認していないので、何かうまく動かない可能性もあります。多分動くと思いますが・・・。
Dim url
As String =
"https://umayadia-apisample.azurewebsites.net/api/persons/Shakespeare" Dim handler As New Net.Http.HttpClientHandler handler.Proxy = System.Net.WebRequest.GetSystemWebProxy 'Windowsで設定されているプロキシー情報からプロキシーを取得します。 'handler.Proxy = New Net.WebProxy("http://proxy.mycompany.net", 8080) '←必要ならプロキシーのアドレスを指定することもできます。 handler.Proxy.Credentials = New Net.NetworkCredential("username", "password") 'handler.Proxy.Credentials = New Net.NetworkCredential("username", "password","company") '←必要ならドメイン名も指定します。この場合、company\username として表記に見慣れているかもしれません。 handler.UseProxy = True Using client As New System.Net.Http.HttpClient(handler) Using response As System.Net.Http.HttpResponseMessage = client.GetAsync(url).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
メモ:この例では人物情報のWebAPIを呼び出して Shakespeare(シェークスピア)の情報を取得します。 → 人物情報のWebAPIについてはこちら
実行するとこのように出力されます。
{"success":true,"data":{"name":"Shakespeare","note":"Hamlet","age":13,"registerDate":"1564-04-26T20:21:00"}} |
参考:HTTPS(SSL)のバージョンを指定する。たとえば、TLS 1.2 や TLS 1.3
SSLのバージョンを指定するには System.Net.ServicePointManager.SecurityProtocol を使用します。そのほかの部分は変更する必要はありません。
'TLS1.2またはTLS1.3を使用するように指定する。 System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls12 Or Net.SecurityProtocolType.Tls13 Dim url As String = "https://umayadia-apisample.azurewebsites.net/api/persons/Shakespeare" Using client As New System.Net.Http.HttpClient() Using response As System.Net.Http.HttpResponseMessage = client.GetAsync(url).Result Dim responseBody As String = response.Content.ReadAsStringAsync().Result Debug.WriteLine(responseBody) End Using End Using |
参考
.NET Framework でのトランスポート層セキュリティ (TLS) のベスト プラクティス | Microsoft Docs
VB6では COMオブジェクトの XMLHttpRequestを使用して、HTTPリクエストを送信することでWebAPIを呼び出せます。