I guys have the following code:
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; }
I use these functions for some method (for example)
async Task<string> login(string url, string id, string pw) {
My problem: if I want to get the result in buttonclick(object sender, EventArgs e) , how can I do this?
I tried this but did not work:
private void buttonclick(object sender, EventArgs e) { string htmlPage=login(url, id, pw); }
EDIT
I solved the problem with adding async between private and void and adding await before login(bla bla)
c # async-await
Tinwor Nov 07 '13 at 10:39
source share