当前位置:
凯发ag旗舰厅登录网址下载 >
编程语言
> c#
>内容正文
c#
c# httpclient编程 -凯发ag旗舰厅登录网址下载
凯发ag旗舰厅登录网址下载
收集整理的这篇文章主要介绍了
c# httpclient编程
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
今天研究了一天c#如何添加cookie到httpcient里面,从而发请求时,能把cookie作为头部发出,最后发现根本加不进去。
httpclient的cookie是来自上一个请求的响应,httpclient会自动把上一个请求的响应里面的cookie保存起来,所以当发送几个有关联的request,就必须要用同一个httpclient
示例:
//第一个请求httpclient client = new httpclient();// 为json格式添加一个accept报头//client.defaultrequestheaders.accept.add(// new mediatypewithqualityheadervalue("application/json"));string strdecodebody = httputility.urlencode(strbody);httpcontent content = new stringcontent(strdecodebody);content.headers.contenttype = new mediatypeheadervalue("application/json");client.defaultrequestheaders.add("user-agent", "mozilla/5.0");client.defaultrequestheaders.add("authentication", "123");httpresponsemessage response = null;response = client.postasync(strip, content).result;if (response != null){if (expectcode == httpstatuscode.ok){var resultvalue = response.content.readasstringasync().result;string strresponse = httputility.urldecode(resultvalue.tostring());string[] strcookies = (string[])response.headers.getvalues("set-cookie");if(strcookies.length>0){strcookie = strcookies[0].substring(0, strcookies[0].indexof(';'));}}}//第二个请求,在这个请求里,没有设置cookie,由于跟第一个请求使用相同httpclient,所以cookie会自动放入请求头部发给服务器string strencodebody = httputility.urlencode(strbody);httpcontent content = new stringcontent(strencodebody);content.headers.contenttype = new mediatypeheadervalue("application/json");httpresponsemessage response = null;response = client.postasync(strip, content).result;if (response != null){if (expectcode == httpstatuscode.ok){var resultvalue = response.content.readasstringasync().result;string strresponse = httputility.urldecode(resultvalue.tostring());return strresponse;}}顶
转载于:https://www.cnblogs.com/shiningrise/p/5931362.html
与50位技术专家面对面20年技术见证,附赠技术全景图总结
以上是凯发ag旗舰厅登录网址下载为你收集整理的c# httpclient编程的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得凯发ag旗舰厅登录网址下载网站内容还不错,欢迎将凯发ag旗舰厅登录网址下载推荐给好友。
- 上一篇:
- 下一篇: