首页 > Windows开发 > 详细

怎么利用C#中的 webclient 创建cookie

时间:2015-09-11 23:19:36      阅读:770      评论:0      收藏:0      [点我收藏+]

Cookies are not limited only to web browsers. any http-aware client that supports cookies can deal with a cookie sending aSp .net Web api. the following code example shows a class extended from WebClient. it overrides the virtual method GetWebRequest to attach an instance of CookieContainer to the request. the CookieContainer object instance has to be reused across the requests to let it push cookies in the subsequent requests. For this reason, it is a class-level field and the same instance of the web client is used to send multiple requests. here we use a proxy of address localhost and port 8888, that of Fiddler, to inspect requests and responses.

public class CookieWebClient : WebClient {    private CookieContainer jar = new CookieContainer(); 
    protected override WebRequest GetWebRequest(Uri address)    {        WebRequest request = base.GetWebRequest(address);                     HttpWebRequest webRequest = request as HttpWebRequest;        if (webRequest != null)            webRequest.CookieContainer = jar;                     return request;    } } 
string url = "http://localhost:7077/api/employees/12345"; 

 


Chapter 4 ■ http anatomy and SeCurity
70
CookieWebClient client = new CookieWebClient() {    Proxy = new WebProxy("localhost", 8888)    // Fiddler };             Console.WriteLine(client.DownloadString(url)); // Cookie is created here Console.WriteLine(client.DownloadString(url)); //  In this request, the cookie gets sent back to the web API

怎么利用C#中的 webclient 创建cookie

原文:http://www.cnblogs.com/haoliansheng/p/4802279.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!