forked from canneverbe/Ketarin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpxRequest.cs
79 lines (67 loc) · 2.55 KB
/
HttpxRequest.cs
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
72
73
74
75
76
77
78
79
using System;
using System.Collections.Specialized;
using System.Net;
using System.Web;
namespace Ketarin
{
/// <summary>
/// Represents an HTTP requests, with further functionality
/// encoded in the URL (like setting Accept headers).
/// </summary>
public class HttpxRequestCreator : IWebRequestCreate
{
#region IWebRequestCreate Member
public WebRequest Create(Uri uri)
{
Uri httpUri = new Uri(uri.ToString().Replace("httpx://", "http://"));
CookieContainer cookies = new CookieContainer();
string accept = null;
string referer = null;
NameValueCollection parameters = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in parameters.AllKeys)
{
if (key == null) continue;
if (key.StartsWith("cookie:"))
{
string name = key.Substring("cookie:".Length);
string value = parameters[key];
cookies.Add(new Cookie(name, value, "/", uri.Host));
parameters.Remove(key);
}
else if (key.StartsWith("header:accept"))
{
accept = parameters[key];
}
else if (key.StartsWith("header:referer"))
{
referer = parameters[key];
}
}
// Remove cookie parameters from URL
string newPathAndQuery = httpUri.PathAndQuery.Substring(0, httpUri.PathAndQuery.Length - httpUri.Query.Length);
string newQuery = string.Empty;
foreach (string key in parameters.AllKeys)
{
newQuery += "&" + HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(parameters[key]);
}
if (newQuery.Length > 0)
{
newQuery = "?" + newQuery.TrimStart('&');
newPathAndQuery = newPathAndQuery + newQuery;
}
httpUri = new Uri(httpUri.Scheme + "://" + httpUri.Host + newPathAndQuery);
HttpWebRequest req = WebRequest.CreateDefault(httpUri) as HttpWebRequest;
req.CookieContainer = cookies;
if (accept != null)
{
req.Accept = accept;
}
if (referer != null)
{
req.Referer = referer;
}
return req;
}
#endregion
}
}