HttpWebResponse

3時間ぐらいずーっと悩んでしまった。HttpWebResponse でhttp接続して、どうやってクッキーの値を取得するのかが全然わからなかった。

string url = "http://....";

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = new CookieContainer();	// <--- ※※※※※※ これが超重要!!!

HttpWebResponse res = (HttpWebResponse)req.GetResponse();
string s = "";

s += "res.CharacterSet; = " + res.CharacterSet;
s += "\n";
s += "res.ContentEncoding; = " + res.ContentEncoding;
s += "\n";
s += "res.ContentLength; = " + res.ContentLength;
s += "\n";
s += "res.ContentType; = " + res.ContentType;
s += "\n";
foreach( Cookie cook in res.Cookies )
{
    s += string.Format("Cookie:\n");
    s += string.Format("{0} = {1}\n",cook.Name,cook.Value);
    s += string.Format("Domain: {0}\n",cook.Domain);
    s += string.Format("Path: {0}\n",cook.Path);
    s += string.Format("Port: {0}\n",cook.Port);
    s += string.Format("Secure: {0}\n",cook.Secure);

    s += string.Format("When issued: {0}\n",cook.TimeStamp);
    s += string.Format("Expires: {0} (expired? {1})\n",cook.Expires,cook.Expired);
    s += string.Format("Don't save: {0}\n",cook.Discard);
    s += string.Format("Comment: {0}\n",cook.Comment);
    s += string.Format("Uri for comments: {0}\n",cook.CommentUri);
    s += string.Format("Version: RFC {0}\n",cook.Version == 1 ? "2109" : "2965");

    // Show the string representation of the cookie.
    s += string.Format("String: {0}\n",cook.ToString());
}
foreach(string key in res.Headers.AllKeys)
{
    s += "Headers: key, value = " + key + ", " + res.Headers.Get(key) + "\n";
}
s += "res.IsFromCache; = " + res.IsFromCache;
s += "\n";
s += "res.IsMutuallyAuthenticated; = " + res.IsMutuallyAuthenticated;
s += "\n";
s += "res.LastModified; = " + res.LastModified;
s += "\n";
s += "res.Method; = " + res.Method;
s += "\n";
s += "res.ProtocolVersion; = " + res.ProtocolVersion;
s += "\n";
s += "res.ResponseUri; = " + res.ResponseUri;
s += "\n";
s += "res.Server; = " + res.Server;
s += "\n";
s += "res.StatusCode; = " + res.StatusCode;
s += "\n";
s += "res.StatusDescription; = " + res.StatusDescription;
MessageBox.Show(s);

res.Close();