指定构成 HTTP 标头的名称/值对的集合。

Headers 集合包含与请求关联的协议标头。下表列出了由系统或由属性或方法设置但未存储在 Headers 中的 HTTP 标头。

 

标头

设置方

Accept

由 Accept 属性设置。

Connection

由 Connection 属性和 KeepAlive 属性设置。

Content-Length

由 ContentLength 属性设置。

Content-Type

由 ContentType 属性设置。

Expect

由 Expect 属性设置。

Date

由系统设置为当前日期。

Host

由系统设置为当前主机信息。

If-Modified-Since

由 IfModifiedSince 属性设置。

Range

由 AddRange 方法设置。

Referer

由 Referer 属性设置。

Transfer-Encoding

由 TransferEncoding 属性设置(SendChunked 属性必须为 true)。

User-Agent

由 UserAgent 属性设置。

如果您试图设置这些受保护的标头之一,则 Add 方法将引发 ArgumentException。

在通过调用 GetRequestStream、BeginGetRequestStream、GetResponse 或 BeginGetResponse 方法启动请求之后,更改 Headers 属性将引发 InvalidOperationException。

不应该假设标头值会保持不变,因为 Web 服务器和缓存可能会更改标头或向 Web 请求添加标头。

  1. // Create a new 'HttpWebRequest' Object to the mentioned URL.
  2. HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
  3. // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
  4. HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
  5. Console.WriteLine("/nThe HttpHeaders are /n/n/tName/t/tValue/n{0}",myHttpWebRequest.Headers);
  6. // Print the HTML contents of the page to the console.
  7. Stream streamResponse=myHttpWebResponse.GetResponseStream();
  8. StreamReader streamRead = new StreamReader( streamResponse );
  9. Char[] readBuff = new Char[256];
  10. int count = streamRead.Read( readBuff, 0, 256 );
  11. Console.WriteLine("/nThe HTML contents of page the are  : /n/n ");
  12. while (count > 0)
  13. {
  14. String outputData = new String(readBuff, 0, count);
  15. Console.Write(outputData);
  16. count = streamRead.Read(readBuff, 0, 256);
  17. }
  18. // Close the Stream object.
  19. streamResponse.Close();
  20. streamRead.Close();
  21. // Release the HttpWebResponse Resource.
  22. myHttpWebResponse.Close();

版权声明:本文为博主原创文章,未经博主允许不得转载。

场景是 winform程序通过HttpWebRequest 调用web Api 接口
其中参数没传过去,有做过这东西的,给点建议。
下面贴代码;

C# code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
 /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
             
            request.Headers.Add("X_REG_CODE", "288a633ccc1");
            request.Headers.Add("X_MACHINE_ID", "a306b7c51254cfc5e22c7ac0702cdf87");
            request.Headers.Add("X_REG_SECRET", "de308301cf381bd4a37a184854035475d4c64946");
            request.Headers.Add("X_STORE", "0001");
            request.Headers.Add("X_BAY", "0001-01");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Accept-Language", "zh-CN");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.Accept = "*/*";
             
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }
 
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
           // if (cookies != null)
           // {
                request.CookieContainer = new CookieContainer();
               // request.CookieContainer.Add(cookies);
           // }
            //如果需要POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
 
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }              
            }   
            HttpWebResponse res;
            try
            {
                res = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
 
            return res;
        }

下面是调用代码

C# code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   public string GetCookies()
        {
            
 
            string url = "http://localhost:17766/Account/LogOn";
 
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("StoreCode", "0001");
            parameters.Add("UserName", "T00000");
            parameters.Add("Password", "123456");
 
             
 
            //string postData = "StoreCode=0001&UserName=T00000&Password=123456";
 
            //HttpWebResponseUtility.PostData(postData, url, null);
 
 
 
            Encoding encoding = Encoding.GetEncoding("gb2312"); 
 
            HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters, null, null, encoding, null);
 
 
 
            String xml = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
 
            return xml;
 
        }

问题:request.Headers;结果:HttpWebRequest.Headers 属性的更多相关文章

  1. C# HTTP系列3 HttpWebRequest.ContentType属性

    系列目录     [已更新最新开发文章,点击查看详细] 获取或设置请求的 Content-type HTTP 标头的值.默认值为null. 常见的请求内容类型为以下几种: /// <summar ...

  2. 在Assertion中获取Response的headers,获取headers中信息,获取body(content)

    // get the  headers of the requestdef content= messageExchange.getResponseContent()def headers = mes ...

  3. C# HTTP系列4 HttpWebRequest.CookieContainer属性

    系列目录     [已更新最新开发文章,点击查看详细] HttpWebRequest.CookieContainer 获取或设置与此请求关联的 Cookie.默认情况下CookieContainer  ...

  4. httpWebRequest.ContentType 属性、值 类型用法

    httpWebRequest.ContentType 属性.值 类型用法 冰火战地 指定将数据回发到服务器时浏览器使用的编码类型.下边是说明: application/x-www-form-urlen ...

  5. HttpWebRequest.ReadWriteTimeout 属性

    获取或设置写入或读取流时的超时. 属性值在写入超时或读取超时之前的毫秒数.默认值为 300,000 毫秒(5 分钟). 备注 在写入由 GetRequestStream 方法返回的流时,或在读取由 G ...

  6. request在作用域中管理属性

    request在作用域中管理属性 制作人:全心全意 在作用域中管理属性 setAttribute(String name,Object object) name:表示变量名,为String类型,在转发 ...

  7. C# HTTP系列7 HttpWebRequest.Method属性

    系列目录     [已更新最新开发文章,点击查看详细] HttpWebRequest.Method属性,获取或设置请求的方法.用于联系 Internet 资源的请求方法. 默认值为 GET. Syst ...

  8. HttpWebRequest.Method 属性

    public static void GetHead(string url) { var http = (HttpWebRequest)WebRequest.Create(url); http.Met ...

  9. Request 对象 response 对象 常见属性

    请求和响应 Express 应用使用回调函数的参数: request 和 response 对象来处理请求和响应的数据. app.get('/', function (req, res) { // - ...

随机推荐

  1. 利用tomcatserver配置https双向认证

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/luo201227/article/details/36897387 首先请保证已经安装好jdk,而且 ...

  2. 说说JSON和JSONP,也许你会豁然开朗,含jQuery用例(转载)

     前言: 说到AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交换数据?第二个是跨域的需求如何解决?这两个问题目前都有不同的解决方案,比如数据可以用自定义字符串或者用XML来描述,跨域 ...

  3. linux 中 用户管理 (composer 时不能root 遇到)

    linux 是支持多用户的,可以同时多个用户在线操作,这点与 Windows 不同. 在我们项目组 操作linux 服务器时,可进行多用户管理,并赋予不同权限,下面是我学习并用的比较频繁的命令: 1. ...

  4. python学习-3.一些常用模块用法

    一.time.datetime 时间戳转化为元组 1 >>> time.localtime() 2 time.struct_time(tm_year=2016, tm_mon=8, ...

  5. Django模型系统——ORM

    一.概论 1.ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说,ORM是通过使用描 ...

  6. php匹配字符串中大写字母的位置

    变量名用的是驼峰,数据库中字段中的是下划线,现在想把userId等变量批量转换成user_id,怎么样获取大写字母在字符串中的位置?echo strtolower(preg_replace('/((? ...

  7. iOS 图文混排 链接 可点击

    对于这个话题 我想到 1 第一个解决方法就是使用 webView 比较经典 把所有复杂工作都交给控件本身去处理了,  但是好像好多需要自定义的地方 没法从 webView获得响应回调 :(估计也可以实 ...

  8. vmware虚拟机安装MAC OSX10.10Yosemite简要记录

    vmware所在环境为win7 64位系统,intel4核CPU,16G内存. 本人安装的是OSX10.10Yosemite的CDR镜像. 1. 在服务中停止所有vmware服务. 2. 安装unlo ...

  9. hiho一下 第四十九周 题目1 : 欧拉路·一【无向图 欧拉路问题】

    题目1 : 欧拉路·一 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho最近在玩一个解密类的游戏,他们需要控制角色在一片原始丛林里面探险,收集道具,并找到最 ...

  10. MyCat:开源分布式数据库中间件

    mycat 的主要配置文件 schema.xml rule.xml server.xml 客户端连接mycat mysql -h192.168.1.1 -P8806 -uroot -pwangxiao ...