VB.NET || How To Send, Post & Process A REST API Web Request ...
Có thể bạn quan tâm
The following is a module with functions which demonstrates how to send and receive a RESTful web request using VB.NET.
Contents
1. Overview1. Overview 2. WebRequest - GET 3. WebRequest - POST 4. WebRequest - PUT 5. WebRequest - PATCH 6. WebRequest - DELETE 7. Utils Namespace 8. More Examples
The following functions use System.Net.HttpWebRequest and System.Net.HttpWebResponse to send and process requests. They can be called synchronously or asynchronously. This page will demonstrate using the asynchronous function calls.
The examples on this page will call a test API, and the resulting calls will return Json results.
The Json objects we are sending to the API are hard coded in the examples below. In a real world application, the objects would be serialized first before they are sent over the network, and then deserialized once a response is received. For simplicity, those operations are hard coded.
For examples of how to serialize and deserialize objects using Json and XML, see below:
- Json – How To Serialize & Deserialize
- XML – How To Serialize & Deserialize
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
2. WebRequest – GETThe example below demonstrates the use of ‘Utils.WebRequest.Get‘ to execute a GET request on the given url.
The optional function parameter allows you to specify System.Net.HttpWebRequest options, like the UserAgent, Headers etc.
2. WebRequest - GET Visual Basic .NET ' WebRequest - GET ' Declare url Dim url = "https://jsonplaceholder.typicode.com/users" ' Optional: Specify request options Dim options = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Execute a get request at the following url Dim response = Await Utils.WebRequest.GetAsync(url) ' Display the status code and response body Debug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") ' .... Do something with response.Body like deserialize it to an object ' expected output: ' Status: 200 - OK ' Bytes Received: 5645 ' Body: [ ' { ' "id": 1, ' "name": "Leanne Graham", ' "username": "Bret", ' "email": "[email protected]", ' "address": { ' "street": "Kulas Light", ' "suite": "Apt. 556", ' "city": "Gwenborough", ' "zipcode": "92998-3874", ' "geo": { ' "lat": "-37.3159", ' "lng": "81.1496" ' } ' }, ' "phone": "1-770-736-8031 x56442", ' "website": "hildegard.org", ' "company": { ' "name": "Romaguera-Crona", ' "catchPhrase": "Multi-layered client-server neural-net", ' "bs": "harness real-time e-markets" ' } ' }, ' { ' "id": 2, ' "name": "Ervin Howell", ' "username": "Antonette", ' "email": "[email protected]", ' "address": { ' "street": "Victor Plains", ' "suite": "Suite 879", ' "city": "Wisokyburgh", ' "zipcode": "90566-7771", ' "geo": { ' "lat": "-43.9509", ' "lng": "-34.4618" ' } ' }, ' "phone": "010-692-6593 x09125", ' "website": "anastasia.net", ' "company": { ' "name": "Deckow-Crist", ' "catchPhrase": "Proactive didactic contingency", ' "bs": "synergize scalable supply-chains" ' } ' }, ' { ' "id": 3, ' "name": "Clementine Bauch", ' "username": "Samantha", ' "email": "[email protected]", ' "address": { ' "street": "Douglas Extension", ' "suite": "Suite 847", ' "city": "McKenziehaven", ' "zipcode": "59590-4157", ' "geo": { ' "lat": "-68.6102", ' "lng": "-47.0653" ' } ' }, ' "phone": "1-463-123-4447", ' "website": "ramiro.info", ' "company": { ' "name": "Romaguera-Jacobson", ' "catchPhrase": "Face to face bifurcated interface", ' "bs": "e-enable strategic applications" ' } ' }, ' { ' "id": 4, ' "name": "Patricia Lebsack", ' "username": "Karianne", ' "email": "[email protected]", ' "address": { ' "street": "Hoeger Mall", ' "suite": "Apt. 692", ' "city": "South Elvis", ' "zipcode": "53919-4257", ' "geo": { ' "lat": "29.4572", ' "lng": "-164.2990" ' } ' }, ' "phone": "493-170-9623 x156", ' "website": "kale.biz", ' "company": { ' "name": "Robel-Corkery", ' "catchPhrase": "Multi-tiered zero tolerance productivity", ' "bs": "transition cutting-edge web services" ' } ' }, ' { ' "id": 5, ' "name": "Chelsey Dietrich", ' "username": "Kamren", ' "email": "[email protected]", ' "address": { ' "street": "Skiles Walks", ' "suite": "Suite 351", ' "city": "Roscoeview", ' "zipcode": "33263", ' "geo": { ' "lat": "-31.8129", ' "lng": "62.5342" ' } ' }, ' "phone": "(254)954-1289", ' "website": "demarco.info", ' "company": { ' "name": "Keebler LLC", ' "catchPhrase": "User-centric fault-tolerant solution", ' "bs": "revolutionize end-to-end systems" ' } ' }, ' { ' "id": 6, ' "name": "Mrs. Dennis Schulist", ' "username": "Leopoldo_Corkery", ' "email": "[email protected]", ' "address": { ' "street": "Norberto Crossing", ' "suite": "Apt. 950", ' "city": "South Christy", ' "zipcode": "23505-1337", ' "geo": { ' "lat": "-71.4197", ' "lng": "71.7478" ' } ' }, ' "phone": "1-477-935-8478 x6430", ' "website": "ola.org", ' "company": { ' "name": "Considine-Lockman", ' "catchPhrase": "Synchronised bottom-line interface", ' "bs": "e-enable innovative applications" ' } ' }, ' { ' "id": 7, ' "name": "Kurtis Weissnat", ' "username": "Elwyn.Skiles", ' "email": "[email protected]", ' "address": { ' "street": "Rex Trail", ' "suite": "Suite 280", ' "city": "Howemouth", ' "zipcode": "58804-1099", ' "geo": { ' "lat": "24.8918", ' "lng": "21.8984" ' } ' }, ' "phone": "210.067.6132", ' "website": "elvis.io", ' "company": { ' "name": "Johns Group", ' "catchPhrase": "Configurable multimedia task-force", ' "bs": "generate enterprise e-tailers" ' } ' }, ' { ' "id": 8, ' "name": "Nicholas Runolfsdottir V", ' "username": "Maxime_Nienow", ' "email": "[email protected]", ' "address": { ' "street": "Ellsworth Summit", ' "suite": "Suite 729", ' "city": "Aliyaview", ' "zipcode": "45169", ' "geo": { ' "lat": "-14.3990", ' "lng": "-120.7677" ' } ' }, ' "phone": "586.493.6943 x140", ' "website": "jacynthe.com", ' "company": { ' "name": "Abernathy Group", ' "catchPhrase": "Implemented secondary concept", ' "bs": "e-enable extensible e-tailers" ' } ' }, ' { ' "id": 9, ' "name": "Glenna Reichert", ' "username": "Delphine", ' "email": "[email protected]", ' "address": { ' "street": "Dayna Park", ' "suite": "Suite 449", ' "city": "Bartholomebury", ' "zipcode": "76495-3109", ' "geo": { ' "lat": "24.6463", ' "lng": "-168.8889" ' } ' }, ' "phone": "(775)976-6794 x41206", ' "website": "conrad.com", ' "company": { ' "name": "Yost and Sons", ' "catchPhrase": "Switchable contextually-based project", ' "bs": "aggregate real-time technologies" ' } ' }, ' { ' "id": 10, ' "name": "Clementina DuBuque", ' "username": "Moriah.Stanton", ' "email": "[email protected]", ' "address": { ' "street": "Kattie Turnpike", ' "suite": "Suite 198", ' "city": "Lebsackbury", ' "zipcode": "31428-2261", ' "geo": { ' "lat": "-38.2386", ' "lng": "57.2232" ' } ' }, ' "phone": "024-648-3804", ' "website": "ambrose.net", ' "company": { ' "name": "Hoeger LLC", ' "catchPhrase": "Centralized empowering task-force", ' "bs": "target end-to-end models" ' } ' } ' ]| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 | ' WebRequest - GET ' Declare urlDimurl="https://jsonplaceholder.typicode.com/users" ' Optional: Specify request optionsDimoptions=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Execute a get request at the following urlDimresponse=Await Utils.WebRequest.GetAsync(url) ' Display the status code and response bodyDebug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body}") ' .... Do something with response.Body like deserialize it to an object ' expected output:' Status: 200 - OK' Bytes Received: 5645' Body: [' {' "id": 1,' "name": "Leanne Graham",' "username": "Bret",' "email": "[email protected]",' "address": {' "street": "Kulas Light",' "suite": "Apt. 556",' "city": "Gwenborough",' "zipcode": "92998-3874",' "geo": {' "lat": "-37.3159",' "lng": "81.1496"' }' },' "phone": "1-770-736-8031 x56442",' "website": "hildegard.org",' "company": {' "name": "Romaguera-Crona",' "catchPhrase": "Multi-layered client-server neural-net",' "bs": "harness real-time e-markets"' }' },' {' "id": 2,' "name": "Ervin Howell",' "username": "Antonette",' "email": "[email protected]",' "address": {' "street": "Victor Plains",' "suite": "Suite 879",' "city": "Wisokyburgh",' "zipcode": "90566-7771",' "geo": {' "lat": "-43.9509",' "lng": "-34.4618"' }' },' "phone": "010-692-6593 x09125",' "website": "anastasia.net",' "company": {' "name": "Deckow-Crist",' "catchPhrase": "Proactive didactic contingency",' "bs": "synergize scalable supply-chains"' }' },' {' "id": 3,' "name": "Clementine Bauch",' "username": "Samantha",' "email": "[email protected]",' "address": {' "street": "Douglas Extension",' "suite": "Suite 847",' "city": "McKenziehaven",' "zipcode": "59590-4157",' "geo": {' "lat": "-68.6102",' "lng": "-47.0653"' }' },' "phone": "1-463-123-4447",' "website": "ramiro.info",' "company": {' "name": "Romaguera-Jacobson",' "catchPhrase": "Face to face bifurcated interface",' "bs": "e-enable strategic applications"' }' },' {' "id": 4,' "name": "Patricia Lebsack",' "username": "Karianne",' "email": "[email protected]",' "address": {' "street": "Hoeger Mall",' "suite": "Apt. 692",' "city": "South Elvis",' "zipcode": "53919-4257",' "geo": {' "lat": "29.4572",' "lng": "-164.2990"' }' },' "phone": "493-170-9623 x156",' "website": "kale.biz",' "company": {' "name": "Robel-Corkery",' "catchPhrase": "Multi-tiered zero tolerance productivity",' "bs": "transition cutting-edge web services"' }' },' {' "id": 5,' "name": "Chelsey Dietrich",' "username": "Kamren",' "email": "[email protected]",' "address": {' "street": "Skiles Walks",' "suite": "Suite 351",' "city": "Roscoeview",' "zipcode": "33263",' "geo": {' "lat": "-31.8129",' "lng": "62.5342"' }' },' "phone": "(254)954-1289",' "website": "demarco.info",' "company": {' "name": "Keebler LLC",' "catchPhrase": "User-centric fault-tolerant solution",' "bs": "revolutionize end-to-end systems"' }' },' {' "id": 6,' "name": "Mrs. Dennis Schulist",' "username": "Leopoldo_Corkery",' "email": "[email protected]",' "address": {' "street": "Norberto Crossing",' "suite": "Apt. 950",' "city": "South Christy",' "zipcode": "23505-1337",' "geo": {' "lat": "-71.4197",' "lng": "71.7478"' }' },' "phone": "1-477-935-8478 x6430",' "website": "ola.org",' "company": {' "name": "Considine-Lockman",' "catchPhrase": "Synchronised bottom-line interface",' "bs": "e-enable innovative applications"' }' },' {' "id": 7,' "name": "Kurtis Weissnat",' "username": "Elwyn.Skiles",' "email": "[email protected]",' "address": {' "street": "Rex Trail",' "suite": "Suite 280",' "city": "Howemouth",' "zipcode": "58804-1099",' "geo": {' "lat": "24.8918",' "lng": "21.8984"' }' },' "phone": "210.067.6132",' "website": "elvis.io",' "company": {' "name": "Johns Group",' "catchPhrase": "Configurable multimedia task-force",' "bs": "generate enterprise e-tailers"' }' },' {' "id": 8,' "name": "Nicholas Runolfsdottir V",' "username": "Maxime_Nienow",' "email": "[email protected]",' "address": {' "street": "Ellsworth Summit",' "suite": "Suite 729",' "city": "Aliyaview",' "zipcode": "45169",' "geo": {' "lat": "-14.3990",' "lng": "-120.7677"' }' },' "phone": "586.493.6943 x140",' "website": "jacynthe.com",' "company": {' "name": "Abernathy Group",' "catchPhrase": "Implemented secondary concept",' "bs": "e-enable extensible e-tailers"' }' },' {' "id": 9,' "name": "Glenna Reichert",' "username": "Delphine",' "email": "[email protected]",' "address": {' "street": "Dayna Park",' "suite": "Suite 449",' "city": "Bartholomebury",' "zipcode": "76495-3109",' "geo": {' "lat": "24.6463",' "lng": "-168.8889"' }' },' "phone": "(775)976-6794 x41206",' "website": "conrad.com",' "company": {' "name": "Yost and Sons",' "catchPhrase": "Switchable contextually-based project",' "bs": "aggregate real-time technologies"' }' },' {' "id": 10,' "name": "Clementina DuBuque",' "username": "Moriah.Stanton",' "email": "[email protected]",' "address": {' "street": "Kattie Turnpike",' "suite": "Suite 198",' "city": "Lebsackbury",' "zipcode": "31428-2261",' "geo": {' "lat": "-38.2386",' "lng": "57.2232"' }' },' "phone": "024-648-3804",' "website": "ambrose.net",' "company": {' "name": "Hoeger LLC",' "catchPhrase": "Centralized empowering task-force",' "bs": "target end-to-end models"' }' }' ] |
The example below demonstrates the use of ‘Utils.WebRequest.Post‘ to execute a POST request on the given url.
The optional function parameter allows you to specify System.Net.HttpWebRequest options, like the UserAgent, Headers etc.
3. WebRequest - POST Visual Basic .NET ' WebRequest - POST ' Declare url Dim url = $"https://jsonplaceholder.typicode.com/users" ' Optional: Specify request options Dim options = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .ContentType = Utils.WebRequest.ContentType.ApplicationJson, .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Serialize object to Json to create a new employee Dim payload = " { ""id"": 0, ""name"": ""Kenneth Perkins"", ""username"": null, ""email"": null, ""address"": null, ""phone"": null, ""website"": null, ""company"": null } " ' Execute a post request at the following url Dim response = Await Utils.WebRequest.PostAsync(url, payload, options) ' Display the status code and response body Debug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") ' .... Do something with response.Body like deserialize it to an object ' expected output: ' Status: 201 - Created ' Bytes Received: 154 ' Body: { ' "id": 11, ' "name": "Kenneth Perkins", ' "username": null, ' "email": null, ' "address": null, ' "phone": null, ' "website": null, ' "company": null ' }| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 | ' WebRequest - POST ' Declare urlDimurl=$"https://jsonplaceholder.typicode.com/users" ' Optional: Specify request optionsDimoptions=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.ContentType=Utils.WebRequest.ContentType.ApplicationJson,.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Serialize object to Json to create a new employeeDimpayload=" { ""id"": 0, ""name"": ""Kenneth Perkins"", ""username"": null, ""email"": null, ""address"": null, ""phone"": null, ""website"": null, ""company"": null }" ' Execute a post request at the following urlDimresponse=Await Utils.WebRequest.PostAsync(url,payload,options) ' Display the status code and response bodyDebug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body}") ' .... Do something with response.Body like deserialize it to an object ' expected output:' Status: 201 - Created' Bytes Received: 154' Body: {' "id": 11,' "name": "Kenneth Perkins",' "username": null,' "email": null,' "address": null,' "phone": null,' "website": null,' "company": null' } |
The example below demonstrates the use of ‘Utils.WebRequest.Put‘ to execute a PUT request on the given url.
The optional function parameter allows you to specify System.Net.HttpWebRequest options, like the UserAgent, Headers etc.
4. WebRequest - PUT Visual Basic .NET ' WebRequest - PUT ' Declare url Dim url = $"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request options Dim options = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .ContentType = Utils.WebRequest.ContentType.ApplicationJson, .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Serialize object to Json to update an existing employee Dim payload = " { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" } " ' Execute a put request at the following url Dim response = Await Utils.WebRequest.PutAsync(url, payload, options) ' Display the status code and response body Debug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") ' .... Do something with response.Body like deserialize it to an object ' expected output: ' Status: 200 - OK ' Bytes Received: 87 ' Body: { ' "name": "Kenneth Perkins", ' "website": "https://www.programmingnotes.org/", ' "id": 1 ' }| 123456789101112131415161718192021222324252627282930313233343536373839404142 | ' WebRequest - PUT ' Declare urlDimurl=$"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request optionsDimoptions=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.ContentType=Utils.WebRequest.ContentType.ApplicationJson,.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Serialize object to Json to update an existing employeeDimpayload=" { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" }" ' Execute a put request at the following urlDimresponse=Await Utils.WebRequest.PutAsync(url,payload,options) ' Display the status code and response bodyDebug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body}") ' .... Do something with response.Body like deserialize it to an object ' expected output:' Status: 200 - OK' Bytes Received: 87' Body: {' "name": "Kenneth Perkins",' "website": "https://www.programmingnotes.org/",' "id": 1' } |
The example below demonstrates the use of ‘Utils.WebRequest.Patch‘ to execute a PATCH request on the given url.
The optional function parameter allows you to specify System.Net.HttpWebRequest options, like the UserAgent, Headers etc.
5. WebRequest - PATCH Visual Basic .NET ' WebRequest - PATCH ' Declare url Dim url = $"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request options Dim options = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .ContentType = Utils.WebRequest.ContentType.ApplicationJson, .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Serialize object to Json to update an existing employee Dim payload = " { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" } " ' Execute a patch request at the following url Dim response = Await Utils.WebRequest.PatchAsync(url, payload, options) ' Display the status code and response body Debug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") ' .... Do something with response.Body like deserialize it to an object ' expected output: ' Status: 200 - OK ' Bytes Received: 526 ' Body: { ' "id": 1, ' "name": "Kenneth Perkins", ' "username": "Bret", ' "email": "[email protected]", ' "address": { ' "street": "Kulas Light", ' "suite": "Apt. 556", ' "city": "Gwenborough", ' "zipcode": "92998-3874", ' "geo": { ' "lat": "-37.3159", ' "lng": "81.1496" ' } ' }, ' "phone": "1-770-736-8031 x56442", ' "website": "https://www.programmingnotes.org/", ' "company": { ' "name": "Romaguera-Crona", ' "catchPhrase": "Multi-layered client-server neural-net", ' "bs": "harness real-time e-markets" ' } ' }| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 | ' WebRequest - PATCH ' Declare urlDimurl=$"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request optionsDimoptions=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.ContentType=Utils.WebRequest.ContentType.ApplicationJson,.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Serialize object to Json to update an existing employeeDimpayload=" { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" }" ' Execute a patch request at the following urlDimresponse=Await Utils.WebRequest.PatchAsync(url,payload,options) ' Display the status code and response bodyDebug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body}") ' .... Do something with response.Body like deserialize it to an object ' expected output:' Status: 200 - OK' Bytes Received: 526' Body: {' "id": 1,' "name": "Kenneth Perkins",' "username": "Bret",' "email": "[email protected]",' "address": {' "street": "Kulas Light",' "suite": "Apt. 556",' "city": "Gwenborough",' "zipcode": "92998-3874",' "geo": {' "lat": "-37.3159",' "lng": "81.1496"' }' },' "phone": "1-770-736-8031 x56442",' "website": "https://www.programmingnotes.org/",' "company": {' "name": "Romaguera-Crona",' "catchPhrase": "Multi-layered client-server neural-net",' "bs": "harness real-time e-markets"' }' } |
The example below demonstrates the use of ‘Utils.WebRequest.Delete‘ to execute a DELETE request on the given url.
The optional function parameter allows you to specify System.Net.HttpWebRequest options, like the UserAgent, Headers etc.
6. WebRequest - DELETE Visual Basic .NET ' WebRequest - DELETE ' Declare url Dim url = $"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request options Dim options = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Execute a delete request at the following url Dim response = Await Utils.WebRequest.DeleteAsync(url, options) ' Display the status code and response body Debug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") ' .... Do something with response.Body like deserialize it to an object ' expected output: ' Status: 200 - OK ' Bytes Received: 2 ' Body: {}| 1234567891011121314151617181920212223242526272829 | ' WebRequest - DELETE ' Declare urlDimurl=$"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request optionsDimoptions=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Execute a delete request at the following urlDimresponse=Await Utils.WebRequest.DeleteAsync(url,options) ' Display the status code and response bodyDebug.Print($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body}") ' .... Do something with response.Body like deserialize it to an object ' expected output:' Status: 200 - OK' Bytes Received: 2' Body: {} |
The following is the Utils Namespace. Include this in your project to start using!
Utils Namespace Visual Basic .NET ' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 18, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Imports System Imports System.Linq Imports System.Threading.Tasks Namespace Global.Utils Namespace WebRequest Public Module modRequest ''' <summary> ''' Executes a GET request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function [Get](url As String _ , Optional options As Options = Nothing) As Response Return GetAsync(url, options:=options).Result End Function ''' <summary> ''' Executes a GET request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function GetAsync(url As String _ , Optional options As Options = Nothing) As Task(Of Response) Return ExecuteAsync(Method.Get, url, payload:=CType(Nothing, Byte()), options:=options) End Function ''' <summary> ''' Executes a POST request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to post to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Post(url As String, payload As String _ , Optional options As Options = Nothing) As Response Return Post(url, payload:=payload.GetBytes, options:=options) End Function ''' <summary> ''' Executes a POST request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to post to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Post(url As String, payload As Byte() _ , Optional options As Options = Nothing) As Response Return PostAsync(url, payload:=payload, options:=options).Result End Function ''' <summary> ''' Executes a POST request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to post to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function PostAsync(url As String, payload As String _ , Optional options As Options = Nothing) As Task(Of Response) Return PostAsync(url, payload:=payload.GetBytes, options:=options) End Function ''' <summary> ''' Executes a POST request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to post to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function PostAsync(url As String, payload As Byte() _ , Optional options As Options = Nothing) As Task(Of Response) Return ExecuteAsync(Method.Post, url, payload:=payload, options:=options) End Function ''' <summary> ''' Executes a PUT request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to put to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Put(url As String, payload As String _ , Optional options As Options = Nothing) As Response Return Put(url, payload:=payload.GetBytes, options:=options) End Function ''' <summary> ''' Executes a PUT request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to put to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Put(url As String, payload As Byte() _ , Optional options As Options = Nothing) As Response Return PutAsync(url, payload:=payload, options:=options).Result End Function ''' <summary> ''' Executes a PUT request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to put to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function PutAsync(url As String, payload As String _ , Optional options As Options = Nothing) As Task(Of Response) Return PutAsync(url, payload:=payload.GetBytes, options:=options) End Function ''' <summary> ''' Executes a PUT request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to put to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function PutAsync(url As String, payload As Byte() _ , Optional options As Options = Nothing) As Task(Of Response) Return ExecuteAsync(Method.Put, url, payload:=payload, options:=options) End Function ''' <summary> ''' Executes a PATCH request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to patch to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Patch(url As String, payload As String _ , Optional options As Options = Nothing) As Response Return Patch(url, payload:=payload.GetBytes, options:=options) End Function ''' <summary> ''' Executes a PATCH request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to patch to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Patch(url As String, payload As Byte() _ , Optional options As Options = Nothing) As Response Return PatchAsync(url, payload:=payload, options:=options).Result End Function ''' <summary> ''' Executes a PATCH request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to patch to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function PatchAsync(url As String, payload As String _ , Optional options As Options = Nothing) As Task(Of Response) Return PatchAsync(url, payload:=payload.GetBytes, options:=options) End Function ''' <summary> ''' Executes a PATCH request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to patch to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function PatchAsync(url As String, payload As Byte() _ , Optional options As Options = Nothing) As Task(Of Response) Return ExecuteAsync(Method.Patch, url, payload:=payload, options:=options) End Function ''' <summary> ''' Executes a DELETE request on the given url ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function Delete(url As String _ , Optional options As Options = Nothing) As Response Return DeleteAsync(url, options:=options).Result End Function ''' <summary> ''' Executes a DELETE request on the given url as an asynchronous operation ''' </summary> ''' <param name="url">The url to navigate to</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function DeleteAsync(url As String _ , Optional options As Options = Nothing) As Task(Of Response) Return ExecuteAsync(Method.Delete, url, payload:=CType(Nothing, Byte()), options:=options) End Function ''' <summary> ''' Executes a request method on the given url as an asynchronous operation ''' </summary> ''' <param name="type">The type of request method to execute</param> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to send to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Function ExecuteAsync(type As Method _ , url As String _ , Optional payload As String = Nothing _ , Optional options As Options = Nothing) As Task(Of Response) Return ExecuteAsync(type, url, payload:=CType(payload?.GetBytes, Byte()), options:=options) End Function ''' <summary> ''' Executes a request method on the given url as an asynchronous operation ''' </summary> ''' <param name="type">The type of request method to execute</param> ''' <param name="url">The url to navigate to</param> ''' <param name="payload">The data to send to the specified resource</param> ''' <param name="options">The options for the web request</param> ''' <returns>The result of the given request</returns> Public Async Function ExecuteAsync(type As Method _ , url As String _ , Optional payload As Byte() = Nothing _ , Optional options As Options = Nothing) As Task(Of Response) Dim request = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest) If options IsNot Nothing Then request.CopyProperties(options) End If request.Method = type.ToString.ToUpper If payload IsNot Nothing Then request.ContentLength = payload.Length Using requestStream = request.GetRequestStream Using payloadStream = New System.IO.MemoryStream(payload) payloadStream.CopyTo(requestStream) End Using End Using End If Dim webResponse As System.Net.HttpWebResponse = Nothing Try webResponse = CType(Await request.GetResponseAsync(), System.Net.HttpWebResponse) Catch ex As System.Net.WebException If ex.Response Is Nothing Then Throw End If webResponse = CType(ex.Response, System.Net.HttpWebResponse) Catch ex As Exception Throw End Try Dim result = New Response With { .Result = webResponse, .Bytes = GetBytes(webResponse) } Return result End Function Private Function GetBytes(response As System.Net.HttpWebResponse) As Byte() Dim bytes As Byte() Dim responseStream = response.GetResponseStream() Using memoryStream = New System.IO.MemoryStream responseStream.CopyTo(memoryStream) bytes = memoryStream.ToArray End Using Return bytes End Function <Runtime.CompilerServices.Extension()> Public Function GetBytes(str As String, Optional encode As System.Text.Encoding = Nothing) As Byte() If encode Is Nothing Then encode = GetDefaultEncoding() End If Return encode.GetBytes(str) End Function <Runtime.CompilerServices.Extension()> Public Function GetString(bytes As Byte(), Optional encode As System.Text.Encoding = Nothing) As String If encode Is Nothing Then encode = GetDefaultEncoding() End If Return encode.GetString(bytes) End Function Private Function GetDefaultEncoding() As System.Text.Encoding Static encode As New System.Text.UTF8Encoding Return encode End Function <Runtime.CompilerServices.Extension()> Private Sub CopyProperties(Of T1, T2)(dest As T1, src As T2) Dim srcProps = src.GetType().GetProperties() Dim destProps = dest.GetType().GetProperties() For Each srcProp In srcProps If srcProp.CanRead Then Dim destProp = destProps.FirstOrDefault(Function(x) x.Name = srcProp.Name) If destProp IsNot Nothing AndAlso destProp.CanWrite Then Dim value = srcProp.GetValue(src, If(srcProp.GetIndexParameters.Count = 1, New Object() {Nothing}, Nothing)) destProp.SetValue(dest, value) End If End If Next End Sub End Module ''' <summary> ''' The response result of a <see cref="System.Net.HttpWebRequest"/> ''' </summary> Public Class Response Public Property Result As System.Net.HttpWebResponse = Nothing Public Property Bytes As Byte() = Nothing Public ReadOnly Property Body As String Get If _body Is Nothing AndAlso Bytes IsNot Nothing Then _body = Bytes.GetString() End If Return _body End Get End Property Private _body As String = Nothing End Class ''' <summary> ''' Options for the given <see cref="System.Net.HttpWebRequest"/> ''' </summary> Public Class Options Public Property Headers As New System.Net.WebHeaderCollection Public Property Credentials As System.Net.ICredentials = Nothing Public Property Connection As String = Nothing Public Property KeepAlive As Boolean = True Public Property Expect As String = Nothing Public Property IfModifiedSince As Date Public Property TransferEncoding As String Public Property Accept As String = Nothing Public Property AllowAutoRedirect As Boolean = True Public Property AllowReadStreamBuffering As Boolean = False Public Property AllowWriteStreamBuffering As Boolean = True Public Property MaximumAutomaticRedirections As Integer = 50 Public Property MediaType As String = Nothing Public Property Pipelined As Boolean = True Public Property PreAuthenticate As Boolean = False Public Property Referer As String = Nothing Public Property SendChunked As Boolean = False Public Property UseDefaultCredentials As Boolean = False Public Property UserAgent As String = Nothing Public Property ContentType As String = Nothing Public Property Timeout As Integer = 100000 Public Property ReadWriteTimeout As Integer = 300000 End Class Public MustInherit Class ContentType Public Const ApplicationUrlEncoded As String = "application/x-www-form-urlencoded" Public Const ApplicationJson As String = "application/json" Public Const TextXml As String = "text/xml" End Class Public Enum Method [Get] Post Put Patch Delete End Enum End Namespace End Namespace ' http://programmingnotes.org/| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 | ' ============================================================================' Author: Kenneth Perkins' Date: Nov 18, 2020' Taken From: http://programmingnotes.org/' File: Utils.vb' Description: Handles general utility functions' ============================================================================OptionStrict OnOptionExplicitOnImportsSystemImportsSystem.LinqImportsSystem.Threading.Tasks Namespace Global.UtilsNamespace WebRequestPublicModulemodRequest''' <summary>''' Executes a GET request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction[Get](url AsString_,Optionaloptions AsOptions=Nothing)AsResponseReturn GetAsync(url,options:=options).ResultEndFunction ''' <summary>''' Executes a GET request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction GetAsync(url AsString_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return ExecuteAsync(Method.Get,url,payload:=CType(Nothing,Byte()),options:=options)EndFunction ''' <summary>''' Executes a POST request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to post to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Post(url AsString,payload AsString_,Optionaloptions AsOptions=Nothing)AsResponseReturn Post(url,payload:=payload.GetBytes,options:=options)EndFunction ''' <summary>''' Executes a POST request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to post to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Post(url AsString,payload AsByte()_,Optionaloptions AsOptions=Nothing)AsResponseReturn PostAsync(url,payload:=payload,options:=options).ResultEndFunction ''' <summary>''' Executes a POST request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to post to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction PostAsync(url AsString,payload AsString_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return PostAsync(url,payload:=payload.GetBytes,options:=options)EndFunction ''' <summary>''' Executes a POST request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to post to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction PostAsync(url AsString,payload AsByte()_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return ExecuteAsync(Method.Post,url,payload:=payload,options:=options)EndFunction ''' <summary>''' Executes a PUT request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to put to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Put(url AsString,payload AsString_,Optionaloptions AsOptions=Nothing)AsResponseReturn Put(url,payload:=payload.GetBytes,options:=options)EndFunction ''' <summary>''' Executes a PUT request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to put to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Put(url AsString,payload AsByte()_,Optionaloptions AsOptions=Nothing)AsResponseReturn PutAsync(url,payload:=payload,options:=options).ResultEndFunction ''' <summary>''' Executes a PUT request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to put to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction PutAsync(url AsString,payload AsString_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return PutAsync(url,payload:=payload.GetBytes,options:=options)EndFunction ''' <summary>''' Executes a PUT request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to put to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction PutAsync(url AsString,payload AsByte()_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return ExecuteAsync(Method.Put,url,payload:=payload,options:=options)EndFunction ''' <summary>''' Executes a PATCH request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to patch to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Patch(url AsString,payload AsString_,Optionaloptions AsOptions=Nothing)AsResponseReturn Patch(url,payload:=payload.GetBytes,options:=options)EndFunction ''' <summary>''' Executes a PATCH request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to patch to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Patch(url AsString,payload AsByte()_,Optionaloptions AsOptions=Nothing)AsResponseReturn PatchAsync(url,payload:=payload,options:=options).ResultEndFunction ''' <summary>''' Executes a PATCH request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to patch to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction PatchAsync(url AsString,payload AsString_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return PatchAsync(url,payload:=payload.GetBytes,options:=options)EndFunction ''' <summary>''' Executes a PATCH request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to patch to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction PatchAsync(url AsString,payload AsByte()_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return ExecuteAsync(Method.Patch,url,payload:=payload,options:=options)EndFunction ''' <summary>''' Executes a DELETE request on the given url''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction Delete(url AsString_,Optionaloptions AsOptions=Nothing)AsResponseReturn DeleteAsync(url,options:=options).ResultEndFunction ''' <summary>''' Executes a DELETE request on the given url as an asynchronous operation''' </summary>''' <param name="url">The url to navigate to</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction DeleteAsync(url AsString_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return ExecuteAsync(Method.Delete,url,payload:=CType(Nothing,Byte()),options:=options)EndFunction ''' <summary>''' Executes a request method on the given url as an asynchronous operation''' </summary>''' <param name="type">The type of request method to execute</param>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to send to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicFunction ExecuteAsync(type AsMethod_,url AsString_,Optionalpayload AsString=Nothing_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Return ExecuteAsync(type,url,payload:=CType(payload?.GetBytes,Byte()),options:=options)EndFunction ''' <summary>''' Executes a request method on the given url as an asynchronous operation''' </summary>''' <param name="type">The type of request method to execute</param>''' <param name="url">The url to navigate to</param>''' <param name="payload">The data to send to the specified resource</param>''' <param name="options">The options for the web request</param>''' <returns>The result of the given request</returns>PublicAsync Function ExecuteAsync(type AsMethod_,url AsString_,Optionalpayload AsByte()=Nothing_,Optionaloptions AsOptions=Nothing)AsTask(Of Response)Dimrequest=CType(System.Net.WebRequest.Create(url),System.Net.HttpWebRequest)If options IsNot NothingThenrequest.CopyProperties(options)EndIfrequest.Method=type.ToString.ToUpper If payload IsNot NothingThenrequest.ContentLength=payload.LengthUsing requestStream=request.GetRequestStreamUsing payloadStream=NewSystem.IO.MemoryStream(payload)payloadStream.CopyTo(requestStream)EndUsingEndUsingEndIf DimwebResponse AsSystem.Net.HttpWebResponse=NothingTrywebResponse=CType(Await request.GetResponseAsync(),System.Net.HttpWebResponse)Catch ex AsSystem.Net.WebExceptionIf ex.Response Is NothingThenThrowEndIfwebResponse=CType(ex.Response,System.Net.HttpWebResponse)Catch ex AsExceptionThrowEndTry Dimresult=NewResponseWith{.Result=webResponse,.Bytes=GetBytes(webResponse)} Return resultEndFunction PrivateFunction GetBytes(response AsSystem.Net.HttpWebResponse)AsByte()Dimbytes AsByte()DimresponseStream=response.GetResponseStream()Using memoryStream=NewSystem.IO.MemoryStreamresponseStream.CopyTo(memoryStream)bytes=memoryStream.ToArrayEndUsingReturn bytesEndFunction <Runtime.CompilerServices.Extension()>PublicFunction GetBytes(str AsString,Optionalencode AsSystem.Text.Encoding=Nothing)AsByte()If encode Is NothingThenencode=GetDefaultEncoding()EndIfReturn encode.GetBytes(str)EndFunction <Runtime.CompilerServices.Extension()>PublicFunction GetString(bytes AsByte(),Optionalencode AsSystem.Text.Encoding=Nothing)AsStringIf encode Is NothingThenencode=GetDefaultEncoding()EndIfReturn encode.GetString(bytes)EndFunction PrivateFunction GetDefaultEncoding()AsSystem.Text.EncodingStatic encode AsNewSystem.Text.UTF8EncodingReturn encodeEndFunction <Runtime.CompilerServices.Extension()>PrivateSubCopyProperties(Of T1,T2)(dest AsT1,src AsT2)DimsrcProps=src.GetType().GetProperties()DimdestProps=dest.GetType().GetProperties()For Each srcProp In srcPropsIf srcProp.CanRead ThenDimdestProp=destProps.FirstOrDefault(Function(x)x.Name=srcProp.Name)If destProp IsNot NothingAndAlsodestProp.CanWrite ThenDimvalue=srcProp.GetValue(src,If(srcProp.GetIndexParameters.Count=1,NewObject(){Nothing},Nothing))destProp.SetValue(dest,value)EndIfEndIfNextEndSubEndModule ''' <summary>''' The response result of a <see cref="System.Net.HttpWebRequest"/> ''' </summary>PublicClassResponsePublicProperty Result AsSystem.Net.HttpWebResponse=NothingPublicProperty Bytes AsByte()=NothingPublicReadOnlyProperty Body AsStringGetIf _body Is NothingAndAlsoBytes IsNot NothingThen_body=Bytes.GetString()EndIfReturn _bodyEndGetEndPropertyPrivate_body AsString=NothingEndClass ''' <summary>''' Options for the given <see cref="System.Net.HttpWebRequest"/> ''' </summary>PublicClassOptionsPublicProperty Headers AsNewSystem.Net.WebHeaderCollectionPublicProperty Credentials AsSystem.Net.ICredentials=NothingPublicProperty Connection AsString=NothingPublicProperty KeepAlive AsBoolean=TruePublicProperty Expect AsString=NothingPublicProperty IfModifiedSince AsDatePublicProperty TransferEncoding AsStringPublicProperty Accept AsString=NothingPublicProperty AllowAutoRedirect AsBoolean=TruePublicProperty AllowReadStreamBuffering AsBoolean=FalsePublicProperty AllowWriteStreamBuffering AsBoolean=TruePublicProperty MaximumAutomaticRedirections AsInteger=50PublicProperty MediaType AsString=NothingPublicProperty Pipelined AsBoolean=TruePublicProperty PreAuthenticate AsBoolean=FalsePublicProperty Referer AsString=NothingPublicProperty SendChunked AsBoolean=FalsePublicProperty UseDefaultCredentials AsBoolean=FalsePublicProperty UserAgent AsString=NothingPublicProperty ContentType AsString=NothingPublicProperty Timeout AsInteger=100000PublicProperty ReadWriteTimeout AsInteger=300000EndClass PublicMustInheritClassContentTypePublicConstApplicationUrlEncoded AsString="application/x-www-form-urlencoded"PublicConstApplicationJson AsString="application/json"PublicConstTextXml AsString="text/xml"EndClass PublicEnum Method[Get]PostPutPatchDeleteEndEnumEndNamespaceEndNamespace' http://programmingnotes.org/ |
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
More Examples Visual Basic .NET ' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 18, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ProcessRequests().Wait() Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Async Function ProcessRequests() As Task ' Declare url Dim url = "https://jsonplaceholder.typicode.com/users" ' Optional: Specify request options Dim options = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Execute a get request at the following url Dim response = Await Utils.WebRequest.GetAsync(url) ' Display the status code and response body Display($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") Display("") ' Declare url Dim url2 = $"https://jsonplaceholder.typicode.com/users" ' Optional: Specify request options Dim options2 = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .ContentType = Utils.WebRequest.ContentType.ApplicationJson, .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Serialize object to get the Json to create a new employee Dim payload = " { ""id"": 0, ""name"": ""Kenneth Perkins"", ""username"": null, ""email"": null, ""address"": null, ""phone"": null, ""website"": null, ""company"": null } " ' Execute a post request at the following url Dim response2 = Await Utils.WebRequest.PostAsync(url2, payload, options2) ' Display the status code and response body Display($" Status: {CInt(response2.Result.StatusCode)} - {response2.Result.StatusDescription} Bytes Received: {response2.Bytes.Length} Body: {response2.Body} ") Display("") ' Declare url Dim url3 = $"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request options Dim options3 = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .ContentType = Utils.WebRequest.ContentType.ApplicationJson, .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Serialize object to Json to update an existing employee Dim payload3 = " { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" } " ' Execute a put request at the following url Dim response3 = Await Utils.WebRequest.PutAsync(url3, payload3, options3) ' Display the status code and response body Display($" Status: {CInt(response3.Result.StatusCode)} - {response3.Result.StatusDescription} Bytes Received: {response3.Bytes.Length} Body: {response3.Body} ") Display("") ' Declare url Dim employeeId = 1 Dim url4 = $"https://jsonplaceholder.typicode.com/users/{employeeId}" ' Optional: Specify request options Dim options4 = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Execute a delete request at the following url Dim response4 = Await Utils.WebRequest.DeleteAsync(url4, options4) ' Display the status code and response body Display($" Status: {CInt(response4.Result.StatusCode)} - {response4.Result.StatusDescription} Bytes Received: {response4.Bytes.Length} Body: {response4.Body} ") Display("") ' Declare url Dim url5 = $"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request options Dim options5 = New Utils.WebRequest.Options With { .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0", .ContentType = Utils.WebRequest.ContentType.ApplicationJson, .Headers = New System.Net.WebHeaderCollection From { {"key", "value"} } } ' Serialize object to Json to update an existing employee Dim payload5 = " { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" } " ' Execute a patch request at the following url Dim response5 = Await Utils.WebRequest.PatchAsync(url5, payload5, options5) ' Display the status code and response body Display($" Status: {CInt(response5.Result.StatusCode)} - {response5.Result.StatusDescription} Bytes Received: {response5.Bytes.Length} Body: {response5.Body} ") End Function Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177 | ' ============================================================================' Author: Kenneth Perkins' Date: Nov 18, 2020' Taken From: http://programmingnotes.org/' File: Program.vb' Description: The following demonstrates the use of the Utils Namespace' ============================================================================OptionStrict OnOptionExplicitOnImportsSystem PublicModuleProgramSubMain(args AsString())TryProcessRequests().Wait()Catch ex AsExceptionDisplay(ex.ToString)FinallyConsole.ReadLine()EndTryEndSub PublicAsync Function ProcessRequests()AsTask' Declare urlDimurl="https://jsonplaceholder.typicode.com/users" ' Optional: Specify request optionsDimoptions=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Execute a get request at the following urlDimresponse=Await Utils.WebRequest.GetAsync(url) ' Display the status code and response bodyDisplay($" Status: {CInt(response.Result.StatusCode)} - {response.Result.StatusDescription} Bytes Received: {response.Bytes.Length} Body: {response.Body} ") Display("") ' Declare urlDimurl2=$"https://jsonplaceholder.typicode.com/users" ' Optional: Specify request optionsDimoptions2=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.ContentType=Utils.WebRequest.ContentType.ApplicationJson,.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Serialize object to get the Json to create a new employeeDimpayload=" { ""id"": 0, ""name"": ""Kenneth Perkins"", ""username"": null, ""email"": null, ""address"": null, ""phone"": null, ""website"": null, ""company"": null } " ' Execute a post request at the following urlDimresponse2=Await Utils.WebRequest.PostAsync(url2,payload,options2) ' Display the status code and response bodyDisplay($" Status: {CInt(response2.Result.StatusCode)} - {response2.Result.StatusDescription} Bytes Received: {response2.Bytes.Length} Body: {response2.Body} ") Display("") ' Declare urlDimurl3=$"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request optionsDimoptions3=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.ContentType=Utils.WebRequest.ContentType.ApplicationJson,.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Serialize object to Json to update an existing employeeDimpayload3=" { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" } " ' Execute a put request at the following urlDimresponse3=Await Utils.WebRequest.PutAsync(url3,payload3,options3) ' Display the status code and response bodyDisplay($" Status: {CInt(response3.Result.StatusCode)} - {response3.Result.StatusDescription} Bytes Received: {response3.Bytes.Length} Body: {response3.Body} ") Display("") ' Declare urlDimemployeeId=1Dimurl4=$"https://jsonplaceholder.typicode.com/users/{employeeId}" ' Optional: Specify request optionsDimoptions4=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Execute a delete request at the following urlDimresponse4=Await Utils.WebRequest.DeleteAsync(url4,options4) ' Display the status code and response bodyDisplay($" Status: {CInt(response4.Result.StatusCode)} - {response4.Result.StatusDescription} Bytes Received: {response4.Bytes.Length} Body: {response4.Body} ") Display("") ' Declare urlDimurl5=$"https://jsonplaceholder.typicode.com/users/1" ' Optional: Specify request optionsDimoptions5=NewUtils.WebRequest.Options With{.UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0",.ContentType=Utils.WebRequest.ContentType.ApplicationJson,.Headers=NewSystem.Net.WebHeaderCollection From{{"key","value"}}} ' Serialize object to Json to update an existing employeeDimpayload5=" { ""name"": ""Kenneth Perkins"", ""website"": ""https://www.programmingnotes.org/"" } " ' Execute a patch request at the following urlDimresponse5=Await Utils.WebRequest.PatchAsync(url5,payload5,options5) ' Display the status code and response bodyDisplay($" Status: {CInt(response5.Result.StatusCode)} - {response5.Result.StatusDescription} Bytes Received: {response5.Bytes.Length} Body: {response5.Body} ")EndFunction PublicSubDisplay(message AsString)Console.WriteLine(message)Debug.Print(message)EndSubEndModule' http://programmingnotes.org/ |
QUICK NOTES: The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Từ khóa » Visual Basic Send Post Request
-
Visual Basic 2010 HTTP POST Request - - Stack Overflow
-
Http Post And Response From Server - CodeProject
-
VB .NET Http Post Request Program Example
-
Making A Post Request With Data In - Shakti Singh Cheema
-
How To: Send Data By Using The WebRequest Class - .NET Framework
-
HttpClient Class (System.Net.Http) | Microsoft Docs
-
Post Json On Url Http Web Request With Vbnet
-
Thread: Send A POST Request Of JSON Content-type - VBForums
-
Thread: Simple HTTP Request - VBForums
-
C# GET/POST Request - ZetCode
-
[VB.NET] Hướng Dẫn Sử Dụng Http Request Post Lấy Facebook ID
-
Http Post Request In Vb.Net - ADocLib
-
JSON HTTP POST Request In Visual Basic .NET · GitHub
-
Http Post Example - CodeNotes - Visual Basic Planet