帶著問題去思考,大家好!
它是什么?它包含什么?它能干什么?
訊息
HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息,
HttpMethod類包含了一組靜態屬性:
private static readonly HttpMethod getMethod = new HttpMethod("GET"); private static readonly HttpMethod putMethod = new HttpMethod("PUT"); private static readonly HttpMethod postMethod = new HttpMethod("POST"); private static readonly HttpMethod deleteMethod = new HttpMethod("DELETE"); private static readonly HttpMethod headMethod = new HttpMethod("HEAD"); private static readonly HttpMethod optionsMethod = new HttpMethod("OPTIONS"); private static readonly HttpMethod traceMethod = new HttpMethod("TRACE")
標頭
- HttpRequestHeaders:包含請求標頭
- HttpResponseHeaders:包含回應標頭
- HttpContentHeaders:包含內容標頭
訊息內容
HttpContent包含了非虛擬公共方法
- Task<string> ReadAsStringAsync()
- Task<byte[]> ReadAsByteArrayAsync()
- Task<Stream> ReadAsStreamAsync()
- Task CopyToAsync(Stream stream, TransportContext context)
第一種方式用于推送方式訪問原始的訊息內容,將一個流傳遞給CopyAsync方法,然后把訊息內容推送到這個流中
using(car client=new HtppClient()) { var response= await client.GetAsync("",HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); var ms=new MemorySteam(); await response.Content.CopyToAsync(ms); Assert.True(ms.Length>0); }
也可以使用ReadAsStreamAsync().拉取方式訪問,這個方法異步回傳一個流
using(var client=new HttpClient()) { var response = await client.GetAsync(""); response.EnsureSuccessStatusCode(); var steam = await response.Content.ReadAsStreamAsync(); var buffer = new byte[2 * 1024]; var len = await steam.ReadAsync(buffer, 0, buffer.Length); }
ReadAsStringAsync和ReadAsByteArrayAsync-異步提供訊息內容的緩沖副本,ReadAsStringAsync回傳原始的位元組內容,ReadAsByteArrayAsync將內容解碼為字串回傳
當然也可以擴展為
public override Task<object> ReadContentAsync(HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/69586.html
標籤:其他
下一篇:Linq操作ArrayList
