私は次のコードを持っています:
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)