Working with HTTP

A WebClient façade class for simple download/upload operations via HTTP or FTP

WebRequest and WebResponse classes for low-level control over client-side HTTP or FTP operations

HttpClient for consuming HTTP web APIs and RESTful services 

1. Concurrent requests

var client = new HttpClient();
var task1 = client.GetStringAsync ("http://www.linqpad.net");
var task2 = client.GetStringAsync ("http://www.albahari.com");
Console.WriteLine (await task1);
Console.WriteLine (await task2);

2. GetAsync and response messages, do handle exception

var client = new HttpClient();
// The GetAsync method also accepts a CancellationToken.
HttpResponseMessageresponse = await client.GetAsync ("http://...");
response.EnsureSuccessStatusCode();
string html = await response.Content.ReadAsStringAsync();

3. SendAsync and request messages

var client = new HttpClient();
var request = new HttpRequestMessage (HttpMethod.Get, "http://...");
HttpResponseMessage response = await client.SendAsync (request);
response.EnsureSuccessStatusCode();

GetAsync is one of four methods corresponding to HTTP’s four verbs (the others are PostAsync, PutAsync, DeleteAsync). 

The four methods are all shortcuts for calling SendAsync, the single low-level method into which everything else feeds.

 

 

posted @ 2013-10-13 16:55  MinieGoGo  阅读(209)  评论(0编辑  收藏  举报