Post请求

 1  //data
2 string cookieStr = "Cookie信息";
3 string postData = string.Format("userid={0}&password={1}", "参数1", "参数2");
4 byte[] data = Encoding.UTF8.GetBytes(postData);
5
6 // Prepare web request...
7 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.xxx.com");
8 request.Method = "POST";
9 //request.Referer = "https://www.xxx.com";
10 request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
11 request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
12 //request.Host = "www.xxx.com";
13 request.Headers.Add("Cookie", cookieStr);
14 request.ContentLength = data.Length;
15 Stream newStream = request.GetRequestStream();
16
17 // Send the data.
18 newStream.Write(data, 0, data.Length);
19 newStream.Close();
20
21 // Get response
22 HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
23 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
24 string content = reader.ReadToEnd();
25 Console.WriteLine(content);
26 Console.ReadLine();
 1 /// <summary>
2 /// 创建POST方式的HTTP请求
3 /// </summary>
4 /// <param name="url">请求的URL</param>
5 /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
6 /// <param name="timeout">请求的超时时间</param>
7 /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
8 /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
9 /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
10 /// <returns></returns>
11 public static HttpWebResponse CreatePostHttpResponse(string url,IDictionary<string,string> parameters,int? timeout, string userAgent,Encoding requestEncoding,CookieCollection cookies)
12 {
13 if (string.IsNullOrEmpty(url))
14 {
15 throw new ArgumentNullException("url");
16 }
17 if(requestEncoding==null)
18 {
19 throw new ArgumentNullException("requestEncoding");
20 }
21 HttpWebRequest request=null;
22 //如果是发送HTTPS请求
23 if(url.StartsWith("https",StringComparison.OrdinalIgnoreCase))
24 {
25 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
26 request = WebRequest.Create(url) as HttpWebRequest;
27 request.ProtocolVersion=HttpVersion.Version10;
28 }
29 else
30 {
31 request = WebRequest.Create(url) as HttpWebRequest;
32 }
33 request.Method = "POST";
34 request.ContentType = "application/x-www-form-urlencoded";
35
36 if (!string.IsNullOrEmpty(userAgent))
37 {
38 request.UserAgent = userAgent;
39 }
40 else
41 {
42 request.UserAgent = DefaultUserAgent;
43 }
44
45 if (timeout.HasValue)
46 {
47 request.Timeout = timeout.Value;
48 }
49 if (cookies != null)
50 {
51 request.CookieContainer = new CookieContainer();
52 request.CookieContainer.Add(cookies);
53 }
54 //如果需要POST数据
55 if(!(parameters==null||parameters.Count==0))
56 {
57 StringBuilder buffer = new StringBuilder();
58 int i = 0;
59 foreach (string key in parameters.Keys)
60 {
61 if (i > 0)
62 {
63 buffer.AppendFormat("&{0}={1}", key, parameters[key]);
64 }
65 else
66 {
67 buffer.AppendFormat("{0}={1}", key, parameters[key]);
68 }
69 i++;
70 }
71 byte[] data = requestEncoding.GetBytes(buffer.ToString());
72 using (Stream stream = request.GetRequestStream())
73 {
74 stream.Write(data, 0, data.Length);
75 }
76 }
77 return request.GetResponse() as HttpWebResponse;
78 }
79 调用
80
81 string loginUrl = "https://passport.baidu.com/?login";
82 string userName = "userName";
83 string password = "password";
84 string tagUrl = "http://cang.baidu.com/"+userName+"/tags";
85 Encoding encoding = Encoding.GetEncoding("gb2312");
86
87 IDictionary<string, string> parameters = new Dictionary<string, string>();
88 parameters.Add("tpl", "fa");
89 parameters.Add("tpl_reg", "fa");
90 parameters.Add("u", tagUrl);
91 parameters.Add("psp_tt", "0");
92 parameters.Add("username", userName);
93 parameters.Add("password", password);
94 parameters.Add("mem_pass", "1");
95 HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, parameters, null, null, encoding, null);
96 string cookieString = response.Headers["Set-Cookie"];

Get请求

 1 /// <summary>
2 /// 创建GET方式的HTTP请求
3 /// </summary>
4 /// <param name="url">请求的URL</param>
5 /// <param name="timeout">请求的超时时间</param>
6 /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
7 /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
8 /// <returns></returns>
9 public static HttpWebResponse CreateGetHttpResponse(string url,int? timeout, string userAgent,CookieCollection cookies)
10 {
11 if (string.IsNullOrEmpty(url))
12 {
13 throw new ArgumentNullException("url");
14 }
15 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
16 request.Method = "GET";
17 request.UserAgent = DefaultUserAgent;
18 if (!string.IsNullOrEmpty(userAgent))
19 {
20 request.UserAgent = userAgent;
21 }
22 if (timeout.HasValue)
23 {
24 request.Timeout = timeout.Value;
25 }
26 if (cookies != null)
27 {
28 request.CookieContainer = new CookieContainer();
29 request.CookieContainer.Add(cookies);
30 }
31 return request.GetResponse() as HttpWebResponse;
32 }
1 string userName = "userName";
2 string tagUrl = "http://cang.baidu.com/"+userName+"/tags";
3 CookieCollection cookies = new CookieCollection();//如何从response.Headers["Set-Cookie"];中获取并设置CookieCollection的代码略
4 response = HttpWebResponseUtility.CreateGetHttpResponse(tagUrl, null, null, cookies);

C# HttpWebRequest Post Get 请求数据的更多相关文章

  1. C# http请求数据

    http中get和post请求的最大区别:get是通过URL传递表单值,post传递的表单值是隐藏到 http报文体中 http以get方式请求数据 /// <summary> /// g ...

  2. 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

    原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...

  3. region URL请求数据

    #region URL请求数据 /// <summary> /// HTTP POST方式请求数据 /// </summary> /// <param name=&quo ...

  4. C#中使用 HttpWebRequest 向网站提交数据

    HttpWebRequest 是 .NET 基类库中的一个类,在命名空间 System.Net 里,用来使用户通过 HTTP 协议和服务器交互. HttpWebRequest 对 HTTP 协议进行了 ...

  5. C#:使用WebRequest类请求数据

    本文翻译于:https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx 下列程序描述的步骤用于从服务器请求一个资源,例如,一个We ...

  6. 获取WebBrowser全cookie 和 httpWebRequest 异步获取页面数据

    获取WebBrowser全cookie [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true) ...

  7. C#实现通过HttpWebRequest发送POST请求实现网站自动登陆

    C#实现通过HttpWebRequest发送POST请求实现网站自动登陆   怎样通过HttpWebRequest 发送 POST 请求到一个网页服务器?例如编写个程序实现自动用户登录,自动提交表单数 ...

  8. C# 应用 - 使用 HttpWebRequest 发起 Http 请求

    helper 类封装 调用 1. 引用的库类 \Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\System.dll Syste ...

  9. 【原生态】Http请求数据 与 发送数据

    今天项目组小弟居然问我怎么用java访问特定的地址获取数据和发送请求 Http请求都是通过输入输出流来进行操作的,首先要制定GET或者POST,默认是GET,在安全和数据量较大情况下请使用post 根 ...

随机推荐

  1. 【WinHec启发录】透过Windows 10技术布局,谈微软王者归来

    每一个时代都有王者,王者的成功,往往是由于恰逢其时地公布了一个成功的产品(具有里程碑意义,划时代的产品).Windows 95的成功标示着微软是PC时代的王者:WinXP的成功标示着微软是互联网时代的 ...

  2. 操作系统学习笔记:CPU调度

    CPU调度的目的在于提高CPU利用率,不让CPU闲着.CPU是宝贵的资源,如果有一个进程,本来在CPU中运行,忽然因为要使用IO资源,于是转而请求IO,这边CPU挂起,造成就绪队列中的其他进程等待,这 ...

  3. ORA-00907: 缺失右括号(通用解决办法)

    PL/SQL 的SQL语句可以执行,但是放在hibernate中,后台打印,出现了错误. 错误的SQL解析:黄色为错误部分 Hibernate:      select         examine ...

  4. python any and all function

    1 any 如果iterable object至少有一个元素是true的时候,返回为true.空的iterable object返回为false. 2 all 如果iterable object中的每 ...

  5. JavaScript中的string interpolation

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals var a = 5; var b ...

  6. BZOJ_2424_[HAOI2010]订货_最小费用最大流

    BZOJ_2424_[HAOI2010]订货_最小费用最大流 Description 某公司估计市场在第i个月对某产品的需求量为Ui,已知在第i月该产品的订货单价为di,上个月月底未销完的单位产品要付 ...

  7. 洛谷 P1084 疫情控制 —— 二分+码力

    题目:https://www.luogu.org/problemnew/show/P1084 5个月前曾经写过一次,某个上学日的深夜,精疲力竭后只有区区10分,从此没管... #include< ...

  8. SYSUCPC2017 1007 Tutu’s Array II

    题目大意:有A个0和B个1,每次取两个出来进行{XNOR,NAND,NOR}操作生成一个新的0/1,直到只剩一个元素.问最后是否可能剩下一个0,是否可能剩下一个1. XNOR 比较特殊 a XNOR ...

  9. vue实例以及生命周期

    1.Vue实例API 1.构造器(实例化) var vm = new Vue({ //选项 |-------DOM(3) |   |-------el (提供一个在页面上已存在的 DOM 元素作为 V ...

  10. 士兵杀敌 三 --- O( 1 ) 的时间复杂度 .

    一看就是 十分简单的  题  ,   然后上去开始无脑程序 超时~~~      感觉时间复杂度 , 已经很低了  ,  但是并没有什么卵用 . #include<stdio.h> #in ...