鼎鼎知识库
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

15.flurl的使用.md 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # url拼接
  2. 拼接`http://www.example.com/endpoint`
  3. ```
  4. //通过string的扩展方法
  5. var url = "http://www.example.com"
  6. .AppendPathSegment("endpoint");
  7. var url = new Url("http://www.example.com").AppendPathSegment();
  8. ```
  9. 查询字符串拼接`http://www.example.com/endpoint/api_key=sth&max_results=sth&q=sth`
  10. ```
  11. var url = "http://www.example.com"
  12. .AppendPathSegment("endpoint")
  13. .SetQueryParams(new {
  14. api_key = sth,
  15. max_results = sth,
  16. q = sth
  17. });
  18. ```
  19. `SetQueryParams`一般会覆盖前面的设置。但是,如果为相同的query变量设置不同的值,可以传入数组或集合。例如:`http://www.example.com/endpoint/x=1&x=2&x=3`
  20. ```
  21. var url = "http://www.example.com"
  22. .SetQueryParams("x", new[]{1, 2, 3});
  23. ```
  24. 关于编码,`flurl`会对查询字符串进行编码,对路径部分的保留字`/`、`%`不会编码,路径部分的空格会编码,路径部分的`?`会编码。
  25. `SetQueryParam`还有一个禁用query编码的重载方法。
  26. ```
  27. var url = "http://www.example.com"
  28. .AppendPathSegment("endpoint")
  29. .SetQueryParam("x", "don%27t%20touch%20m", true)
  30. ```
  31. 默认会把空格编码成`%20`,但有时候希望把空格编码成`+`。
  32. ```
  33. var url = "http://www.example.com"
  34. .AppendPathSegment("endpoint")
  35. .SetQueryParam("x","hi")
  36. .ToString(true);
  37. ```
  38. 取出url地址中的不同部分,例如`http://www.example.com/with/path?x=1&y=3#foo`
  39. ```
  40. var url = new Url("http://www.example.com/with/path?x=1&y=3#foo");
  41. var path = url.Path;//http://www.example.com/with/path
  42. var query= url.Query;//x=1&y=3
  43. var paramVal = url.QueryParams["y"];//3
  44. var fragment = url.Fragment; //foo
  45. ```
  46. 多个url部分拼接。
  47. ```
  48. //http://www.foo.com/too/many/few?x=1&y=2
  49. var url = Url.Combine("http://foo.com/","/too/","/many/","few?","x=1","y=2");
  50. ```
  51. 其它API
  52. ```
  53. string Path{get;set;}
  54. string Query Fragment{get;set;}
  55. QueryParamCollectio QueryParams{get;}
  56. Url AppendPathSegment();
  57. Url SetQueryParam();
  58. Url RemoveQueryParams();
  59. Url SetFragment();
  60. Url RemoveFragment();
  61. Url ResetToRoot();
  62. bool IsValid();
  63. string ToString(bool encodeSpaceAsPlus);
  64. string Combine(params string[] parts);
  65. QueryParamCollection ParseQueryParams(string query);
  66. string GetRoot(string url);
  67. string DecodeQueryParamValue(string value);
  68. string EncodeQueryParamValue(object value, bool encodeSpaceAsPlus);
  69. string EncodeILlegalCharacter(strint urlPart);
  70. ```
  71. # Fluent HTTP
  72. 需要引用两个插件
  73. ```
  74. using Flurl;
  75. using Flurl.Http;
  76. ```
  77. 发送一般请求:
  78. ```
  79. var getResp = await "".GetAsync();
  80. ```
  81. 发动GET请求:
  82. ```
  83. var headResp = await "".HeadAsync();
  84. ```
  85. 获取强类型
  86. ```
  87. T poco = await "".GetJsonAsync<T>();
  88. dynamic d = await "".GetJsonAsync();
  89. var list = await "".GetJsonListAsync();
  90. ```
  91. 获取string
  92. ```
  93. string text = await "".GetStringAsync();
  94. ```
  95. 获取bytes
  96. ```
  97. byte[] bytes = await "".GetBytesAsync();
  98. ```
  99. 获取流
  100. ```
  101. Stream stream = await "".GetStreamAsync();
  102. ```
  103. 下载文件
  104. ```
  105. var path = await "http://files.foo.com/image.jpg"
  106. .DownloadFileAsync("c:\\downloads", filename);
  107. ```
  108. 发送json数据
  109. ```
  110. await "".PostJsonAsync(new {a=1,b=2});
  111. ```
  112. 设置headers
  113. ```
  114. await url.WithHeader("Accept","text/plain").GetJsonAsync();
  115. await url.WithHeaders(new {Accept="text/plain", User_Agent=""}).GetJosnAsync();
  116. ```
  117. 设置验证
  118. ```
  119. 一般验证:await url.WithBasicAuth("","").GetJsonAsync();
  120. OAUth验证:await url.WithOAuthBearerToken("mytoken").GetJsonAsync();
  121. ```
  122. 设置过期时间
  123. ```
  124. await url.WithTimeout(10).DownloadFileAsync(); //10秒
  125. await url.WithTimeout(TimeSpan.FromMinutes(2)).DownloadFileAsync();
  126. ```
  127. 设置cookie
  128. ```
  129. await url.WithCookie("name","value", expDate).HeadAsync();
  130. await url.WithCookies(new {c1=1, c2=2}, expDate).HeadAsync();
  131. ```
  132. 取消请求
  133. ```
  134. var cts = new CancellationTokenSource();
  135. var task = url.GetAsync(cts.Token);
  136. cts.Cancel();
  137. ```
  138. 发送表单数据
  139. ```
  140. await "".PostUrlEncodeAsync(new {user = "", pass=""});
  141. ```
  142. 发送表单数据,并且处理返回结果
  143. ```
  144. T poco = await url.PostJsonAsync(data).ReceiveJson<T>();
  145. dynamic d = await url.PostUrlEncodeAsync(data).ReceiveJson();
  146. string s = await url.PostUrlEncodeAsync(data).ReceiveString();
  147. ```
  148. 使用原生的`HttpClient`
  149. ```
  150. await url.PostAsync(httpContent);
  151. await url.SendJsonAsync(HttpMethod.Options, poco);
  152. await url.SendAsync(HttpMethod.Trace, httpContent, cancellationToken,HttpCompletionOption.ResponseHeaderRead);
  153. ```
  154. # 异常处理
  155. 一般处理,适用于XXX异常
  156. ```
  157. try{
  158. await url.PostJsonAsync(poco);
  159. }
  160. catch(FlurlHttpTimeoutException){
  161. LogError("timeout");
  162. }
  163. catch(FlurHttpException ex){
  164. LogError(ex.Message);
  165. }
  166. ```
  167. 使用扩展方法处理异常,适用于XXX异常
  168. ```
  169. catch(FlurlHttpException ex){
  170. TError e = ex.GetResponseJson<TError>();
  171. dynamic d = ex.GetResponseJson();
  172. }
  173. ```
  174. 允许除了2XX的异常
  175. ```
  176. url.AllowHttpStatus(HttpStatusCode.NotFound, HttpStatusCode.Conflict).GetAsync();
  177. url.AllowHttpStatus("400-404,6xx").GetAsync();
  178. url.AllowAnyHttpStatus().GetAsync();
  179. ```