【问题标题】:Send Cookies with HTTPWebRequestion through WP8 App通过 WP8 应用使用 HTTPWebRequestion 发送 Cookie
【发布时间】:2014-02-12 04:16:32
【问题描述】:

我必须为每个后续的 HTTPWebRequest 发送 cookie 到服务器。我的代码如下。

class APIManager
{

CookieContainer cookieJar = new CookieContainer();
CookieCollection responseCookies = new CookieCollection();

private async Task<string> httpRequest(HttpWebRequest request)
{
    string received;

    using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
        .FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
    {
        using (var responseStream = response.GetResponseStream())
        {
            using (var sr = new StreamReader(responseStream))
            {
                cookieJar = request.CookieContainer;
                responseCookies = response.Cookies;
                received = await sr.ReadToEndAsync();
            }
        }
    }

    return received;
}

public async Task<string> Get(string path)
{
    var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
    request.CookieContainer = cookieJar;

    return await httpRequest(request);
}

public async Task<string> Post(string path, string postdata)
{
    var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
    request.Method = "POST";
    request.CookieContainer = cookieJar;

    byte[] data = Encoding.UTF8.GetBytes(postdata);
    using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
    {
        await requestStream.WriteAsync(data, 0, data.Length);
    }

    return await httpRequest(request);
}

}

每次我提出问题时,人们都说我必须通过以下代码行设置带有请求的 cookie 容器。

  request.CookieContainer = cookieJar;

我使用了它,但服务器仍然返回“令牌不匹配”错误。我需要与供应商交谈吗?

下图显示了我的问题和要求。

【问题讨论】:

    标签: json cookies windows-phone-8 httpwebrequest


    【解决方案1】:

    我还没有看到你用 cookieJar 做点什么!

    //Create the cookie container and add a cookie.
    request.CookieContainer = new CookieContainer();
    
    // This example shows manually adding a cookie, but you would most
    // likely read the cookies from isolated storage.
    request.CookieContainer.Add(new Uri("http://api.search.live.net"),
    new Cookie("id", "1234"));
    

    您的 APIManager 中的cookieJar 是一个成员,每次您的实例 APIManager 时,cookieJar 都是一个新实例。您需要确保cookieJar 包含网站所需的内容。

    你可以看看这个How to: Get and Set Cookies

    【讨论】:

    • 你有一只鹰眼,实际上代码是旧的。我将 cookiejar 更改为静态并验证它在下一次调用时计数为 3。请让我知道将其设为静态是否可行,或者我应该保留 domain-ii(cookie 供应商告诉要保留)然后每次都发送?
    • 当前代码是私有静态CookieContainer cookieJar = new CookieContainer();
    • 静态成员仍然可以共享,因为静态成员属于类而不是实例。
    • @LojiSmithKaleem 你可以试试 request.Headers["Cookie"]="your cookie";
    • request.CookieContainer.Add(new Uri("http://.com", UriKind.Absolute), responseCookies["cookietitle"]);
    猜你喜欢
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多