您可以使用网络浏览器控件使用虚假的网络点击事件等登录(您似乎已经这样做了,+1)
然后,您可以将 cookie 从 webbrowser 控件传输到 webrequest 以做更多理智的事情。您也可以缓存 cookie 以备后用
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
namespace Sample.Helpers {
public class NativeMethods {
public static CookieContainer GetUriCookieContainer(Uri uri) {
CookieContainer cookies = null;
int datasize = 8192 * 16; // Determine the size of the cookie
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero)) {
if (datasize < 0)
return null;
cookieData = new StringBuilder(datasize); // Allocate stringbuilder large enough to hold the cookie
if (!InternetGetCookieEx(
uri.ToString(),
null, cookieData,
ref datasize,
InternetCookieHttponly,
IntPtr.Zero))
return null;
}
if (cookieData.Length > 0) {
cookies = new CookieContainer();
cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
}
return cookies;
}
[DllImport("wininet.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true)]
private static extern bool InternetGetCookieEx(string url, string cookieName, StringBuilder cookieData, ref int size, Int32 dwFlags, IntPtr lpReserved);
private const Int32 InternetCookieHttponly = 0x2000;
}
}
示例用法
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.CookieContainer = Cookies;
//webRequest.Headers.Add(HeaderCollection);
webRequest.Timeout = 10000;
//webRequest.UserAgent = UserAgent;
webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
webRequest.Method = "POST";
byte[] postBytes;
if (postDataRaw != null) {
postBytes = Encoding.UTF8.GetBytes(postDataRaw);
}
webRequest.ContentLength = postBytes.Length;
using (var dataStream = webRequest.GetRequestStream()) {
dataStream.Write(postBytes, 0, postBytes.Length);
}
using (var response = webRequest.GetResponse()) {
var result = ((HttpWebResponse)response).StatusCode;
using (var responseStream = response.GetResponseStream()) {
using (var streamReader = new StreamReader(responseStream)) {
return streamReader.ReadToEnd();
}
}
}