伙计们,我有以下代码:
public static CookieContainer cookies;
public static HttpWebRequest GetNewRequest(string targetUrl, CookieContainer SessionCookieContainer)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
request.CookieContainer = SessionCookieContainer;
request.AllowAutoRedirect = false;
return request;
}
public async static Task<HttpWebResponse> MakeRequest(HttpWebRequest request, CookieContainer SessionCookieContainer, Dictionary<string, string> parameters = null)
{
HttpWebResponse response;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5Accept: */*";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.CookieContainer = SessionCookieContainer;
request.AllowAutoRedirect = false;
if (parameters != null)
{
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string s = "";
foreach (KeyValuePair<string, string> pair in parameters)
{
if (s.Length == 0)
{
s = s + string.Format("{0}={1}", pair.Key, pair.Value);
}
else
{
s = s + string.Format("&{0}={1}", pair.Key, pair.Value);
}
}
byte[] bytes = Encoding.UTF8.GetBytes(s);
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(bytes, 0, bytes.Length);
}
}
request.Method = "GET";
response = await request.GetResponseAsync() as HttpWebResponse;
SessionCookieContainer.Add(response.Cookies);
while (response.StatusCode == HttpStatusCode.Found)
{
response.Close();
request = GetNewRequest(response.Headers["Location"], SessionCookieContainer);
response = await request.GetResponseAsync() as HttpWebResponse;
SessionCookieContainer.Add(response.Cookies);
}
return response;
}
我使用这个函数的一些方法(例如)
async Task<string> login(string url, string id, string pw)
{
///code...
}
我的问题是:如果我想得到结果buttonclick(object sender, EventArgs e)
我该怎么办?
我已经尝试过了,但是没有用:
private void buttonclick(object sender, EventArgs e)
{
string htmlPage=login(url, id, pw);
}
编辑
我已经解决了在和 voidasync
之间添加和在之前添加的问题private
await
login(bla bla)