More Group Sites
Education Books
School Rankings
Jobless Net
Better Home
Enviro++
更好教育论坛


Help | Subscribe/Unsubscribe | Rules | Other Group Sites: Better Education | Better Education Forum
Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Share
Options
View
Go to last post Go to first unread
hong  
#1 Posted : Friday, 21 September 2018 9:53:49 PM(UTC)
hong

Rank: Administration

Reputation:

Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 519

HttpClient is preferred to WebClient or HttpWebRequest / WebRequest

In .NET, there are three different classes HttpWebRequest, WebClient, HttpClient to consume REST APIs. Which one to choose?

The key differences are
+ HttpWebRequest for more control
+ WebClient for simplicity
+ HttpClient for both plus async features

Conclusion: HttpClient is preferred to WebClient or HttpWebRequest.

HttpClient PostAsync and PutAsync
POST is used to create. The PUT method requests that the enclosed entity be stored under the supplied Request-URI.
Code:
            var parameters = new Dictionary<string, string>
            {
                { "p1", "param1" }, { "p2", "param2" }
            };

            parameters["p3"] = "param3";

            //more parameters can be added

            var encodedContent = new FormUrlEncodedContent(parameters);

            using (var client = new HttpClient { MaxResponseContentBufferSize = 256000 })
            {
                _client.DefaultRequestHeaders
                .Accept
                .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

                //PostAsync or PutAsync accordingly, POST is used to create. The PUT method requests that the enclosed entity be stored under the supplied Request-URI
                var response = await client.PostAsync(url, encodedContent).ConfigureAwait(false);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // Do something with response. Example get content:
                    //var responseContent = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
                    //var responseContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                    var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    //eg JsonConvert.DeserializeObject...
                }
                else
                {
                    //handle the error
                }
            }

Edited by user Monday, 24 September 2018 9:59:41 PM(UTC)  | Reason: Not specified

Sponsor
hong  
#2 Posted : Monday, 24 September 2018 9:31:10 PM(UTC)
hong

Rank: Administration

Reputation:

Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 519

HttpClient Delete using SendAsync

Code:
            var parameters = new Dictionary<string, string>
            {
                { "p1", "param1" }, { "p2", "param2" }
            };

            parameters["p3"] = "param3";

            //more parameters can be added
            var encodedContent = new FormUrlEncodedContent(parameters);

            HttpRequestMessage requestMessage = new HttpRequestMessage
            {
                Content = encodedContent,
                Method = HttpMethod.Delete,
                RequestUri = new Uri("<uri>")
            };

            using (var client = new HttpClient { MaxResponseContentBufferSize = 256000 })
            {
                var response = await client.SendAsync(requestMessage);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    //...
                }
                else
                {
                    //handle the error
                }
            }

Edited by user Monday, 24 September 2018 9:53:25 PM(UTC)  | Reason: Not specified

hong  
#3 Posted : Monday, 24 September 2018 9:57:48 PM(UTC)
hong

Rank: Administration

Reputation:

Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor
Joined: 23/11/2008(UTC)
Posts: 519

Does HttpClient have to be disposed (with Using block)?

The general consensus is that you do not (should not) need to dispose of HttpClient.

If the response messages are quite small (usually under 2GB), it is not necessary to dispose the HttpResponseMessages.

Quote:
Although HttpClient does indirectly implement the IDisposable interface, the standard usage of HttpClient is not to dispose of it after every request.

The HttpClient object is intended to live for as long as your application needs to make HTTP requests.

Having an object exist across multiple requests enables a place for setting DefaultRequestHeaders and prevents you from having to re-specify things like CredentialCache and CookieContainer on every request as was necessary with HttpWebRequest.


Rss Feed  Atom Feed
Users browsing this topic
Guest (2)
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.