发现.NET Framework 3.5 等旧版本不支持 HttpWebRequest.Date ,但是我想修改Http 头部Date的值,怎么办,
之前没有, 那就扩展一下啊。
public static class HttpWebRequestExtensions { static string[] RestrictedHeaders = new string[] { "Accept", "Connection", "Content-Length", "Content-Type", "Date", "Expect", "Host", "If-Modified-Since", "Range", "Referer", "Transfer-Encoding", "User-Agent", "Proxy-Connection" }; static Dictionary<string, PropertyInfo> HeaderProperties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); static HttpWebRequestExtensions() { Type type = typeof(HttpWebRequest); foreach (string header in RestrictedHeaders) { string propertyName = header.Replace("-", ""); PropertyInfo headerProperty = type.GetProperty(propertyName); HeaderProperties[header] = headerProperty; } } public static void SetRawHeader(this HttpWebRequest request, string name, string value) { if (HeaderProperties.ContainsKey(name)) { HeaderProperties[name].SetValue(request, value, null); } else { request.Headers[name] = value; } } }
那就扩展一下。
使用
HttpWebRequest request = WebRequest.Create("www.gaomn.com") as HttpWebRequest; request.SetRawHeader("Date", XXXXXXXXX);
你可以使用 WebRequest
WebRequest web = WebRequest.Create(url);
WebHeaderCollection webc = new WebHeaderCollection();
webc.Add("Date", dateGMT);
web.Headers = webc;
同学,这样写也是不允许的。
HttpClient
.NET Framework 3.5 你告诉我用HttpClient?