forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebRequestExtensions.cs
More file actions
71 lines (64 loc) · 2.41 KB
/
Copy pathWebRequestExtensions.cs
File metadata and controls
71 lines (64 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.IO;
using System.Net;
namespace ServiceStack.Text
{
public static class WebRequestExtensions
{
public static string GetJsonFromUrl(this string url, Action<HttpWebResponse> responseFilter = null)
{
return url.GetStringFromUrl("application/json", responseFilter);
}
public static string GetStringFromUrl(this string url, string acceptContentType = "*/*", Action<HttpWebResponse> responseFilter = null)
{
var webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.Accept = acceptContentType;
webReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var webRes = webReq.GetResponse())
using (var stream = webRes.GetResponseStream())
using (var reader = new StreamReader(stream))
{
if (responseFilter != null)
{
responseFilter((HttpWebResponse)webRes);
}
return reader.ReadToEnd();
}
}
public static bool Is404(this Exception ex)
{
return HasStatus(ex as WebException, HttpStatusCode.NotFound);
}
public static HttpStatusCode? GetResponseStatus(this string url)
{
try
{
var webReq = (HttpWebRequest)WebRequest.Create(url);
using (var webRes = webReq.GetResponse())
{
var httpRes = webRes as HttpWebResponse;
return httpRes != null ? httpRes.StatusCode : (HttpStatusCode?)null;
}
}
catch (Exception ex)
{
return ex.GetStatus();
}
}
public static HttpStatusCode? GetStatus(this Exception ex)
{
return GetStatus(ex as WebException);
}
public static HttpStatusCode? GetStatus(this WebException webEx)
{
if (webEx == null) return null;
var httpRes = webEx.Response as HttpWebResponse;
return httpRes != null ? httpRes.StatusCode : (HttpStatusCode?)null;
}
public static bool HasStatus(this WebException webEx, HttpStatusCode statusCode)
{
return GetStatus(webEx) == statusCode;
}
}
}