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

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 classCookieWebClient : WebClient

{private CookieContainer jar = newCookieContainer();protected overrideWebRequest GetWebRequest(Uri address)

{

WebRequest request= base.GetWebRequest(address);

HttpWebRequest webRequest= request asHttpWebRequest;if (webRequest != null)

webRequest.CookieContainer=jar;returnrequest;

}

}public classTestClass

{public voidMyTestMethod()

{string url = "http://localhost:7077/api/employees/12345";

CookieWebClient client= newCookieWebClient()

{

Proxy= new WebProxy("localhost", 8888) //Fiddler

};

Console.WriteLine(client.DownloadString(url));//In this request, the cookie gets sent back to the web API

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值