2014-01-22 39 views
0

我必须发送cookie到服务器为每个后续的HTTPWebRequest。我的代码在下面。通过WP8发送Cookie与HTTPWebRequestion应用

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; 

和我用它,但仍然服务器返回'令牌不匹配'的错误。我需要与供应商沟通吗?

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

enter image description here

回答

0

我没有看到你做的东西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

+0

你有鹰眼,其实代码是旧的一个。我将cookiejar更改为静态,并验证下一次调用已计入3。请让我知道,如果使它静态将工作,或者我应该坚持域 - ii(cookie供应商告诉坚持),然后每次发送它? – LojiSmith

+0

当前的代码是私有的静态CookieContainer cookieJar = new CookieContainer(); – LojiSmith

+0

静态成员仍然可以共享,因为静态成员属于类而不是实例。 – AlexisXu