5

HttpWebRequest クラスで POST Web リクエストをシミュレートしようとしています:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(<my url>));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        request.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";

リクエスト用の Cookie を設定する必要があります。私は方法を試しました:

request.Headers.Add(HttpRequestHeader.Cookie, GetGlobalCookies(<cookies url>));

 [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
    const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

    public static string GetGlobalCookies(string uri)
    {
        uint datasize = 1024;
        StringBuilder cookieData = new StringBuilder((int)datasize);
        if (InternetGetCookieEx(uri, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)
            && cookieData.Length > 0) {
            return cookieData.ToString(); //.Replace(';', ',');
        }
        else
        {
            return null;
        }
    }

request.CookieContainer = new CookieContainer();
request.CookieContainer.SetCookies(new Uri(<my url>), GetGlobalCookies(<cookies-url>).Replace(';', ','));

GetGlobalCookies() は、必要な Cookie を含む正しい文字列を返します。しかし、 requset.GetResponse() を実行した後、フィドラーでのリクエストは次のようになります。

POST <my url> HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: <my host>
Content-Length: 3
Expect: 100-continue
Connection: Keep-Alive

i=1

Method を GET に変更すると、Cookie は正しく送信されますが、User-Agent は送信されません。

GET <my url> HTTP/1.1
Cookie: ASP.NET_SessionId=uajwt1ybpde4hudwwizuq2ld
Host: <my host>
Connection: Keep-Alive

HttpWebRequest が Cookie および User-Agent ヘッダーを送信しないのはなぜですか?

4

1 に答える 1