码迷,mamicode.com
首页 > Windows程序 > 详细

C# WebRequest

时间:2019-06-12 19:39:04      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:sign   次数   private   start   owa   转化   pac   begin   hid   

HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。另外,你可能预计需要显式地调用一个“Send”方法,实际上不需要。接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。

这种技术展示了如何限制请求重定向(request redirections)的次数, 并且设置了一个超时限制。下面是HttpWebRequest的一些属性,这些属性对于轻量级的自动化测试程序是非常重要的。

l  AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。

l  CookieContainer:获取或设置与此请求关联的cookie。

l  Credentials:获取或设置请求的身份验证信息。

l  KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。

l  MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。

l  Proxy:获取或设置请求的代理信息。

l  SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。

l  Timeout:获取或设置请求的超时值。

l  UserAgent:获取或设置 User-agent HTTP 标头的值

C# HttpWebRequest提交数据方式其实就是GET和POST两种,那么具体的实现以及操作注意事项是什么呢?那么本文就向你详细介绍C# HttpWebRequest提交数据方式的这两种利器。

C# HttpWebRequest提交数据方式学习之前我们先来看看什么是HttpWebRequest,它是 .net 基类库中的一个类,在命名空间 System.Net 下面,用来使用户通过HTTP协议和服务器交互。

C# HttpWebRequest的作用:

HttpWebRequest对HTTP协议进行了完整的封装,对HTTP协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。

C# HttpWebRequest提交数据方式:

程序使用HTTP协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成,下面对这两种方式进行一下说明:

C# HttpWebRequest提交数据方式1. GET 方式。

GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 http://www.google.com/webhp?hl=zh-CN 中,前面部分 http://www.google.com/webhp 表示数据提交的网址,后面部分 hl=zh-CN 表示附加的参数,其中 hl 表示一个键(key), zh-CN 表示这个键对应的值(value)。程序代码如下:

HttpWebRequest req =  

(HttpWebRequest) HttpWebRequest.Create(  

"http://www.google.com/webhp?hl=zh-CN" ); 

req.Method = "GET"; 

using (WebResponse wr = req.GetResponse()) 

   //在这里对接收到的页面内容进行处理 

}

C# HttpWebRequest提交数据方式2. POST 方式。

POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。程序代码如下:

string param = "hl=zh-CN&newwindow=1";        //参数

byte[] bs = Encoding.ASCII.GetBytes(param);    //参数转化为ascii码

HttpWebRequest req =   (HttpWebRequest) HttpWebRequest.Create(   "http://www.google.com/intl/zh-CN/" );  //创建request

req.Method = "POST";    //确定传值的方式,此处为post方式传值

req.ContentType = "application/x-www-form-urlencoded"; 

req.ContentLength = bs.Length; 

using (Stream reqStream = req.GetRequestStream()) 

   reqStream.Write(bs, 0, bs.Length); 

using (WebResponse wr = req.GetResponse()) 

   //在这里对接收到的页面内容进行处理 

在上面的代码中,我们访问了 www.google.com 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。

C# HttpWebRequest提交数据方式3. 使用 GET 方式提交中文数据。

GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种,用 gb2312 方式编码访问的程序代码如下:

Encoding myEncoding = Encoding.GetEncoding("gb2312");     //确定用哪种中文编码方式

string address = "http://www.baidu.com/s?"   + HttpUtility.UrlEncode("参数一", myEncoding) +  "=" + HttpUtility.UrlEncode("值一", myEncoding);       //拼接数据提交的网址和经过中文编码后的中文参数

HttpWebRequest req =   (HttpWebRequest)HttpWebRequest.Create(address);  //创建request

req.Method = "GET";    //确定传值方式,此处为get方式

using (WebResponse wr = req.GetResponse()) 

   //在这里对接收到的页面内容进行处理 

在上面的程序代码中,我们以 GET 方式访问了网址 http://www.baidu.com/s ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。常见的网站中, www.baidu.com (百度)的编码方式是 gb2312, www.google.com (谷歌)的编码方式是 utf8。

C# HttpWebRequest提交数据方式4. 使用 POST 方式提交中文数据。

POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。用 gb2312 方式编码访问的程序代码如下:

Encoding myEncoding = Encoding.GetEncoding("gb2312");  //确定中文编码方式。此处用gb2312

string param =   HttpUtility.UrlEncode("参数一", myEncoding) +   "=" + HttpUtility.UrlEncode("值一", myEncoding) +   "&" +     HttpUtility.UrlEncode("参数二", myEncoding) +  "=" + HttpUtility.UrlEncode("值二", myEncoding); 

byte[] postBytes = Encoding.ASCII.GetBytes(param);     //将参数转化为assic码

HttpWebRequest req = (HttpWebRequest)  HttpWebRequest.Create( "http://www.baidu.com/s" ); 

req.Method = "POST"; 

req.ContentType =   "application/x-www-form-urlencoded;charset=gb2312"; 

req.ContentLength = postBytes.Length; 

using (Stream reqStream = req.GetRequestStream()) 

   reqStream.Write(bs, 0, bs.Length); 

using (WebResponse wr = req.GetResponse()) 

   //在这里对接收到的页面内容进行处理 

}  

从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。

以上列出了客户端程序使用HTTP协议与服务器交互的情况,常用的是 GET 和 POST 方式。现在流行的 WebService 也是通过 HTTP 协议来交互的,使用的是 POST 方法。与以上稍有所不同的是, WebService 提交的数据内容和接收到的数据内容都是使用了 XML 方式编码。所以, HttpWebRequest 也可以使用在调用 WebService 的情况下。

 

技术图片
 1 #region 公共方法
 2         /// <summary>
 3         /// Get数据接口
 4         /// </summary>
 5         /// <param name="getUrl">接口地址</param>
 6         /// <returns></returns>
 7         private static string GetWebRequest(string getUrl)
 8         {
 9             string responseContent = "";
10 
11             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
12             request.ContentType = "application/json";
13             request.Method = "GET";
14 
15             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
16             //在这里对接收到的页面内容进行处理
17             using (Stream resStream = response.GetResponseStream())
18             {
19                 using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
20                 {
21                     responseContent = reader.ReadToEnd().ToString();
22                 }
23             }
24             return responseContent;
25         }
26         /// <summary>
27         /// Post数据接口
28         /// </summary>
29         /// <param name="postUrl">接口地址</param>
30         /// <param name="paramData">提交json数据</param>
31         /// <param name="dataEncode">编码方式(Encoding.UTF8)</param>
32         /// <returns></returns>
33         private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
34         {
35             string responseContent = string.Empty;
36             try
37             {
38                 byte[] byteArray = dataEncode.GetBytes(paramData); //转化
39                 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
40                 webReq.Method = "POST";
41                 webReq.ContentType = "application/x-www-form-urlencoded";
42                 webReq.ContentLength = byteArray.Length;
43                 using (Stream reqStream = webReq.GetRequestStream())
44                 {
45                     reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
46                     //reqStream.Close();
47                 }
48                 using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
49                 {
50                     //在这里对接收到的页面内容进行处理
51                     using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
52                     {
53                         responseContent = sr.ReadToEnd().ToString();
54                     }
55                 }
56             }
57             catch (Exception ex)
58             {
59                 return ex.Message;
60             }
61             return responseContent;
62         }
63 
64         #endregion
View Code

post支持cookie

技术图片
 1 /// <summary>
 2         /// 发起Post请求(采用HttpWebRequest,支持传Cookie)
 3         /// </summary>
 4         /// <param name="strUrl">请求Url</param>
 5         /// <param name="formData">发送的表单数据</param>
 6         /// <param name="strResult">返回请求结果(如果请求失败,返回异常消息)</param>
 7         /// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
 8         /// <returns>返回:是否请求成功</returns>
 9         public static bool HttpPost(string strUrl, Dictionary<string, string> formData, CookieContainer cookieContainer, out string strResult)
10         {
11             string strPostData = null;
12             if (formData != null && formData.Count > 0)
13             {
14                 StringBuilder sbData = new StringBuilder();
15                 int i = 0;
16                 foreach (KeyValuePair<string, string> data in formData)
17                 {
18                     if (i > 0)
19                     {
20                         sbData.Append("&");
21                     }
22                     sbData.AppendFormat("{0}={1}", data.Key, data.Value);
23                     i++;
24                 }
25                 strPostData = sbData.ToString();
26             }
27 
28             byte[] postBytes = string.IsNullOrEmpty(strPostData) ? new byte[0] : Encoding.UTF8.GetBytes(strPostData);
29 
30             return HttpPost(strUrl, postBytes, cookieContainer, out strResult);
31         }
View Code

post上传文件

技术图片
 1 /// <summary>
 2         /// 发起Post文件请求(采用HttpWebRequest,支持传Cookie)
 3         /// </summary>
 4         /// <param name="strUrl">请求Url</param>
 5         /// <param name="strFilePostName">上传文件的PostName</param>
 6         /// <param name="strFilePath">上传文件路径</param>
 7         /// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
 8         /// <param name="strResult">返回请求结果(如果请求失败,返回异常消息)</param>
 9         /// <returns>返回:是否请求成功</returns>
10         public static bool HttpPostFile(string strUrl, string strFilePostName, string strFilePath, CookieContainer cookieContainer, out string strResult)
11         {
12             HttpWebRequest request = null;
13             FileStream fileStream = FileHelper.GetFileStream(strFilePath);
14 
15             try
16             {
17                 if (fileStream == null)
18                 {
19                     throw new FileNotFoundException();
20                 }
21 
22                 request = (HttpWebRequest)WebRequest.Create(strUrl);
23                 request.Method = "POST";
24                 request.KeepAlive = false;
25                 request.Timeout = 30000;
26 
27                 if (cookieContainer != null)
28                 {
29                     request.CookieContainer = cookieContainer;
30                 }
31 
32                 string boundary = string.Format("---------------------------{0}", DateTime.Now.Ticks.ToString("x"));
33 
34                 byte[] header = Encoding.UTF8.GetBytes(string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n",
35                     boundary, strFilePostName, Path.GetFileName(strFilePath)));
36                 byte[] footer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary));
37 
38                 request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
39                 request.ContentLength = header.Length + fileStream.Length + footer.Length;
40 
41                 using (Stream reqStream = request.GetRequestStream())
42                 {
43                     // 写入分割线及数据信息
44                     reqStream.Write(header, 0, header.Length);
45 
46                     // 写入文件
47                     FileHelper.WriteFile(reqStream, fileStream);
48 
49                     // 写入尾部
50                     reqStream.Write(footer, 0, footer.Length);
51                 }
52 
53                 strResult = GetResponseResult(request, cookieContainer);
54             }
55             catch (Exception ex)
56             {
57                 strResult = ex.Message;
58                 return false;
59             }
60             finally
61             {
62                 if (request != null)
63                 {
64                     request.Abort();
65                 }
66                 if (fileStream != null)
67                 {
68                     fileStream.Close();
69                 }
70             }
71 
72             return true;
73         }
74 
75 
76         /// <summary>
77         /// 获取请求结果字符串
78         /// </summary>
79         /// <param name="request">请求对象(发起请求之后)</param>
80         /// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
81         /// <returns>返回请求结果字符串</returns>
82         private static string GetResponseResult(HttpWebRequest request, CookieContainer cookieContainer = null)
83         {
84             using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
85             {
86                 if (cookieContainer != null)
87                 {
88                     response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
89                 }
90                 using (Stream rspStream = response.GetResponseStream())
91                 {
92                     using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
93                     {
94                         return reader.ReadToEnd();
95                     }
96                 }
97             }
98         }
View Code

OAuth头部 

 

技术图片
 1 //构造OAuth头部 
 2 StringBuilder oauthHeader = new StringBuilder(); 
 3 oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey); 
 4 oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce); 
 5 oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp); 
 6 oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1"); 
 7 oauthHeader.AppendFormat("oauth_version={0}, ", "1.0"); 
 8 oauthHeader.AppendFormat("oauth_signature={0}, ", sig); 
 9 oauthHeader.AppendFormat("oauth_token={0}", accessToken); 
10 
11 //构造请求 
12 StringBuilder requestBody = new StringBuilder(""); 
13 Encoding encoding = Encoding.GetEncoding("utf-8"); 
14 byte[] data = encoding.GetBytes(requestBody.ToString()); 
15 
16 // Http Request的设置 
17 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
18 request.Headers.Set("Authorization", oauthHeader.ToString());
19 //request.Headers.Add("Authorization", authorization); 
20 request.ContentType = "application/atom+xml"; 
21 request.Method = "GET"; 
View Code

https://www.cnblogs.com/shadowtale/p/3372735.html

技术图片
  1 1.POST方法(httpWebRequest)
  2 
  3  
  4 
  5 
  6 
  7 //body是要传递的参数,格式"roleId=1&uid=2"
  8 //post的cotentType填写:"application/x-www-form-urlencoded"
  9 //soap填写:"text/xml; charset=utf-8"
 10     public static string PostHttp(string url, string body, string contentType)
 11     {
 12         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
 13 
 14         httpWebRequest.ContentType = contentType;
 15         httpWebRequest.Method = "POST";
 16         httpWebRequest.Timeout = 20000;
 17 
 18         byte[] btBodys = Encoding.UTF8.GetBytes(body);
 19         httpWebRequest.ContentLength = btBodys.Length;
 20         httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
 21 
 22         HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
 23         StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
 24         string responseContent = streamReader.ReadToEnd();
 25 
 26         httpWebResponse.Close();
 27         streamReader.Close();
 28         httpWebRequest.Abort();
 29         httpWebResponse.Close();
 30 
 31         return responseContent;
 32     }
 33 
 34 POST方法(httpWebRequest)
 35 
 36 
 37 2.POST方法(WebClient)
 38 
 39 
 40 
 41 /// <summary>
 42         /// 通过WebClient类Post数据到远程地址,需要Basic认证;
 43         /// 调用端自己处理异常
 44         /// </summary>
 45         /// <param name="uri"></param>
 46         /// <param name="paramStr">name=张三&age=20</param>
 47         /// <param name="encoding">请先确认目标网页的编码方式</param>
 48         /// <param name="username"></param>
 49         /// <param name="password"></param>
 50         /// <returns></returns>
 51         public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
 52         {
 53             if (encoding == null)
 54                 encoding = Encoding.UTF8;
 55 
 56             string result = string.Empty;
 57 
 58             WebClient wc = new WebClient();
 59 
 60             // 采取POST方式必须加的Header
 61             wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
 62 
 63             byte[] postData = encoding.GetBytes(paramStr);
 64 
 65             if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
 66             {
 67                 wc.Credentials = GetCredentialCache(uri, username, password);
 68                 wc.Headers.Add("Authorization", GetAuthorization(username, password));
 69             }
 70 
 71             byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
 72             return encoding.GetString(responseData);// 解码                  
 73         }
 74 
 75 POST方法(WebClient)
 76 
 77 3.Get方法(httpWebRequest)
 78 
 79 
 80 
 81 public static string GetHttp(string url, HttpContext httpContext)
 82     {
 83         string queryString = "?";
 84 
 85         foreach (string key in httpContext.Request.QueryString.AllKeys)
 86         {
 87             queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
 88         }
 89 
 90         queryString = queryString.Substring(0, queryString.Length - 1);
 91 
 92         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
 93 
 94         httpWebRequest.ContentType = "application/json";
 95         httpWebRequest.Method = "GET";
 96         httpWebRequest.Timeout = 20000;
 97 
 98         //byte[] btBodys = Encoding.UTF8.GetBytes(body);
 99         //httpWebRequest.ContentLength = btBodys.Length;
100         //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
101 
102         HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
103         StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
104         string responseContent = streamReader.ReadToEnd();
105 
106         httpWebResponse.Close();
107         streamReader.Close();
108 
109         return responseContent;
110     }
111 
112 Get方法(HttpWebRequest)
113 
114 4.basic验证的WebRequest/WebResponse
115 
116 
117 
118 /// <summary>
119         /// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
120         /// 调用端自己处理异常
121         /// </summary>
122         /// <param name="uri"></param>
123         /// <param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>
124         /// <param name="encoding">如果不知道具体的编码,传入null</param>
125         /// <param name="username"></param>
126         /// <param name="password"></param>
127         /// <returns></returns>
128         public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
129         {
130             string result = string.Empty;
131 
132             WebRequest request = WebRequest.Create(new Uri(uri));
133 
134             if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
135             {
136                 request.Credentials = GetCredentialCache(uri, username, password);
137                 request.Headers.Add("Authorization", GetAuthorization(username, password));
138             }
139 
140             if (timeout > 0)
141                 request.Timeout = timeout;
142 
143             WebResponse response = request.GetResponse();
144             Stream stream = response.GetResponseStream();
145             StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
146 
147             result = sr.ReadToEnd();
148 
149             sr.Close();
150             stream.Close();
151 
152             return result;
153         }
154 
155         #region # 生成 Http Basic 访问凭证 #
156 
157         private static CredentialCache GetCredentialCache(string uri, string username, string password)
158         {
159             string authorization = string.Format("{0}:{1}", username, password);
160 
161             CredentialCache credCache = new CredentialCache();
162             credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
163 
164             return credCache;
165         }
166 
167         private static string GetAuthorization(string username, string password)
168         {
169             string authorization = string.Format("{0}:{1}", username, password);
170 
171             return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
172         }
173 
174         #endregion
175 
176 basic验证的WebRequest/WebResponse
177 
178  
179 
180 C#语言写的关于HttpWebRequest 类的使用方法
181 
182 http://www.jb51.net/article/57156.htm
183 
184 
185 
186 using System;
187 
188 using System.Collections.Generic;
189 
190 using System.IO;
191 
192 using System.Net;
193 
194 using System.Text;
195 
196 namespace HttpWeb
197 
198 {
199 
200     /// <summary> 
201 
202     ///  Http操作类 
203 
204     /// </summary> 
205 
206     public static class httptest
207 
208     {
209 
210         /// <summary> 
211 
212         ///  获取网址HTML 
213 
214         /// </summary> 
215 
216         /// <param name="URL">网址 </param> 
217 
218         /// <returns> </returns> 
219 
220         public static string GetHtml(string URL)
221 
222         {
223 
224             WebRequest wrt;
225 
226             wrt = WebRequest.Create(URL);
227 
228             wrt.Credentials = CredentialCache.DefaultCredentials;
229 
230             WebResponse wrp;
231 
232             wrp = wrt.GetResponse();
233 
234             string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
235 
236             try
237 
238             {
239 
240                 wrt.GetResponse().Close();
241 
242             }
243 
244             catch (WebException ex)
245 
246             {
247 
248                 throw ex;
249 
250             }
251 
252             return reader;
253 
254         }
255 
256         /// <summary> 
257 
258         /// 获取网站cookie 
259 
260         /// </summary> 
261 
262         /// <param name="URL">网址 </param> 
263 
264         /// <param name="cookie">cookie </param> 
265 
266         /// <returns> </returns> 
267 
268         public static string GetHtml(string URL, out string cookie)
269 
270         {
271 
272             WebRequest wrt;
273 
274             wrt = WebRequest.Create(URL);
275 
276             wrt.Credentials = CredentialCache.DefaultCredentials;
277 
278             WebResponse wrp;
279 
280             wrp = wrt.GetResponse();
281             string html = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
282 
283             try
284 
285             {
286 
287                 wrt.GetResponse().Close();
288 
289             }
290 
291             catch (WebException ex)
292 
293             {
294 
295                 throw ex;
296 
297             }
298 
299             cookie = wrp.Headers.Get("Set-Cookie");
300 
301             return html;
302 
303         }
304 
305         public static string GetHtml(string URL, string postData, string cookie, out string header, string server)
306 
307         {
308 
309             return GetHtml(server, URL, postData, cookie, out header);
310 
311         }
312 
313         public static string GetHtml(string server, string URL, string postData, string cookie, out string header)
314 
315         {
316 
317             byte[] byteRequest = Encoding.GetEncoding("gb2312").GetBytes(postData);
318 
319             return GetHtml(server, URL, byteRequest, cookie, out header);
320 
321         }
322 
323         public static string GetHtml(string server, string URL, byte[] byteRequest, string cookie, out string header)
324 
325         {
326 
327             byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header);
328 
329             Stream getStream = new MemoryStream(bytes);
330 
331             StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
332 
333             string getString = streamReader.ReadToEnd();
334 
335             streamReader.Close();
336 
337             getStream.Close();
338 
339             return getString;
340 
341         }
342 
343         /// <summary> 
344 
345         /// Post模式浏览 
346 
347         /// </summary> 
348 
349         /// <param name="server">服务器地址 </param> 
350 
351         /// <param name="URL">网址 </param> 
352 
353         /// <param name="byteRequest"></param> 
354 
355         /// <param name="cookie">cookie </param> 
356 
357         /// <param name="header">句柄 </param> 
358 
359         /// <returns> </returns> 
360 
361         public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header)
362 
363         {
364 
365             long contentLength;
366 
367             HttpWebRequest httpWebRequest;
368 
369             HttpWebResponse webResponse;
370 
371             Stream getStream;
372 
373             httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
374 
375             CookieContainer co = new CookieContainer();
376 
377             co.SetCookies(new Uri(server), cookie);
378 
379             httpWebRequest.CookieContainer = co;
380 
381             httpWebRequest.ContentType = "application/x-www-form-urlencoded";
382 
383             httpWebRequest.Accept =
384 
385                 "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
386 
387             httpWebRequest.Referer = server;
388 
389             httpWebRequest.UserAgent =
390 
391                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
392 
393             httpWebRequest.Method = "Post";
394 
395             httpWebRequest.ContentLength = byteRequest.Length;
396 
397             Stream stream;
398 
399             stream = httpWebRequest.GetRequestStream();
400 
401             stream.Write(byteRequest, 0, byteRequest.Length);
402 
403             stream.Close();
404 
405             webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
406 
407             header = webResponse.Headers.ToString();
408 
409             getStream = webResponse.GetResponseStream();
410 
411             contentLength = webResponse.ContentLength;
412 
413             byte[] outBytes = new byte[contentLength];
414 
415             outBytes = ReadFully(getStream);
416 
417             getStream.Close();
418 
419             return outBytes;
420 
421         }
422 
423         public static byte[] ReadFully(Stream stream)
424 
425         {
426 
427             byte[] buffer = new byte[128];
428 
429             using (MemoryStream ms = new MemoryStream())
430 
431             {
432 
433                 while (true)
434 
435                 {
436 
437                     int read = stream.Read(buffer, 0, buffer.Length);
438 
439                     if (read <= 0)
440 
441                         return ms.ToArray();
442 
443                     ms.Write(buffer, 0, read);
444 
445                 }
446 
447             }
448 
449         }
450 
451         /// <summary> 
452 
453         /// Get模式 
454 
455         /// </summary> 
456 
457         /// <param name="URL">网址 </param> 
458 
459         /// <param name="cookie">cookies </param> 
460 
461         /// <param name="header">句柄 </param> 
462 
463         /// <param name="server">服务器 </param> 
464 
465         /// <param name="val">服务器 </param> 
466 
467         /// <returns> </returns> 
468 
469         public static string GetHtml(string URL, string cookie, out string header, string server)
470 
471         {
472 
473             return GetHtml(URL, cookie, out header, server, "");
474 
475         }
476 
477         /// <summary> 
478 
479         /// Get模式浏览 
480 
481         /// </summary> 
482 
483         /// <param name="URL">Get网址 </param> 
484 
485         /// <param name="cookie">cookie </param> 
486 
487         /// <param name="header">句柄 </param> 
488 
489         /// <param name="server">服务器地址 </param> 
490 
491         /// <param name="val"> </param> 
492 
493         /// <returns> </returns> 
494 
495         public static string GetHtml(string URL, string cookie, out string header, string server, string val)
496 
497         {
498 
499             HttpWebRequest httpWebRequest;
500 
501             HttpWebResponse webResponse;
502 
503             Stream getStream;
504 
505             StreamReader streamReader;
506 
507             string getString = "";
508 
509             httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
510 
511             httpWebRequest.Accept = "*/*";
512 
513             httpWebRequest.Referer = server;
514 
515             CookieContainer co = new CookieContainer();
516 
517             co.SetCookies(new Uri(server), cookie);
518 
519             httpWebRequest.CookieContainer = co;
520 
521             httpWebRequest.UserAgent =
522 
523                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
524 
525             httpWebRequest.Method = "GET";
526 
527             webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
528 
529             header = webResponse.Headers.ToString();
530 
531             getStream = webResponse.GetResponseStream();
532 
533             streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
534 
535             getString = streamReader.ReadToEnd();
536 
537             streamReader.Close();
538 
539             getStream.Close();
540 
541             return getString;
542 
543         }
544 
545    }
546 
547 }
548 
549  有空查看:
550 
551 
552 
553     /// <summary>
554     /// 作用描述: WebRequest操作类
555     /// </summary>
556     public static class CallWebRequest
557     {
558         /// <summary>
559         /// 通过GET请求获取数据
560         /// </summary>
561         /// <param name="url"></param>
562         /// <returns></returns>
563         public static string Get(string url)
564         {
565             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
566             //每次请求绕过代理,解决第一次调用慢的问题
567             request.Proxy = null;
568             //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
569             ServicePoint currentServicePoint = request.ServicePoint;
570             currentServicePoint.ConnectionLimit = 1000;
571             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
572             string str;
573             using (Stream responseStream = response.GetResponseStream())
574             {
575                 Encoding encode = Encoding.GetEncoding("utf-8");
576                 StreamReader reader = new StreamReader(responseStream, encode);
577                 str = reader.ReadToEnd();          
578             }
579             response.Close();
580             response = null;
581             request.Abort();
582             request = null;
583             return str;
584         }
585 
586         /// <summary>
587         /// 通过POST请求传递数据
588         /// </summary>
589         /// <param name="url"></param>
590         /// <param name="postData"></param>
591         /// <returns></returns>
592         public static string Post(string url, string postData)
593         {
594             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
595 
596             //将发送数据转换为二进制格式
597             byte[] byteArray = Encoding.UTF8.GetBytes(postData);
598             //要POST的数据大于1024字节的时候, 浏览器并不会直接就发起POST请求, 而是会分为俩步:
599             //1. 发送一个请求, 包含一个Expect:100-continue, 询问Server使用愿意接受数据
600             //2. 接收到Server返回的100-continue应答以后, 才把数据POST给Server
601             //直接关闭第一步验证
602             request.ServicePoint.Expect100Continue = false;
603             //是否使用Nagle:不使用,提高效率 
604             request.ServicePoint.UseNagleAlgorithm = false;
605             //设置最大连接数
606             request.ServicePoint.ConnectionLimit = 65500;
607             //指定压缩方法
608             //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
609             request.KeepAlive = false;
610             //request.ContentType = "application/json";
611             request.ContentType = "application/x-www-form-urlencoded";
612             
613             request.Method = "POST";
614             request.Timeout = 20000;
615             request.ContentLength = byteArray.Length;
616             //关闭缓存
617             request.AllowWriteStreamBuffering = false;
618 
619             //每次请求绕过代理,解决第一次调用慢的问题
620             request.Proxy = null;
621             //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
622             ServicePoint currentServicePoint = request.ServicePoint;
623 
624             Stream dataStream = request.GetRequestStream();
625             dataStream.Write(byteArray, 0, byteArray.Length);
626             dataStream.Close();
627 
628             WebResponse response = request.GetResponse();
629             //获取服务器返回的数据流
630             dataStream = response.GetResponseStream();
631             StreamReader reader = new StreamReader(dataStream);
632             string responseFromServer = reader.ReadToEnd();
633             reader.Close();
634             dataStream.Close();
635             request.Abort();
636             response.Close();
637             reader.Dispose();
638             dataStream.Dispose();
639             return responseFromServer;
640         }
641     }
642 
643  
644 
645 
646 
647     /// <summary>
648     /// 用于外部接口调用封装
649     /// </summary>
650     public static class ApiInterface
651     {
652 
653         /// <summary>
654         ///验证密码是否正确
655         /// </summary>
656         public static Api_ToConfig<object> checkPwd(int userId, string old)
657         {
658             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkPwd";
659             var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId, "&oldPwd=" + old));
660             //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}"));
661             return data;
662         }
663 
664         /// <summary>
665         ///
666         /// </summary>
667         public static Api_ToConfig<object> UpdatePassword(int userId, string pwd, string old)
668         {
669             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updatePwd";
670             var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId + "&oldPwd=" + old, "&newPwd=" + pwd));
671             //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}"));
672             return data;
673         }
674 
675 
676 
677 
678         private static DateTime GetTime(string timeStamp)
679         {
680             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
681             long lTime = long.Parse(timeStamp + "0000");
682             TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
683         }
684 
685 
686         #region 公共方法
687 
688         /// <summary>
689         /// 配置文件key
690         /// </summary>
691         /// <param name="key"></param>
692         /// <param name="isOutKey"></param>
693         /// <returns></returns>
694         public static string GetConfig(string key, bool isOutKey = false)
695         {
696             //  CacheRedis.Cache.RemoveObject(RedisKey.ConfigList);
697             var data = CacheRedis.Cache.Get<Api_BaseToConfig<Api_Config>>(RedisKey.ConfigList);
698 
699             //  var data = new Api_BaseToConfig<Api_Config>();
700             if (data == null)
701             {
702                 string dataCenterUrl = WebConfigManager.GetAppSettings("DataCenterUrl");
703                 string configurationInfoListByFilter = WebConfigManager.GetAppSettings("ConfigurationInfoListByFilter");
704 
705                 string systemCoding = WebConfigManager.GetAppSettings("SystemCoding");
706                 string nodeIdentifier = WebConfigManager.GetAppSettings("NodeIdentifier");
707                 string para = "systemIdf=" + systemCoding + "&nodeIdf=" + nodeIdentifier + "";
708                 //string para = "{\"systemIdf\":\"" + systemCoding + "\",\"nodeIdf\":\"" + nodeIdentifier + "\"}";
709 
710                 string result = CallWebRequest.Post(dataCenterUrl + "/rest" + configurationInfoListByFilter, para);
711                 data =
712                     Json.ToObject<Api_BaseToConfig<Api_Config>>(result);
713                 CacheRedis.Cache.Set(RedisKey.ConfigList, data);
714             }
715             if (data.Status)
716             {
717                 if (isOutKey && ConfigServer.IsOutside())
718                 {
719                     key += "_outside";
720                 }
721                 key = key.ToLower();
722                 var firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier.ToLower() == key);
723                 if (firstOrDefault != null)
724                 {
725                     return firstOrDefault.Value;
726                 }
727                 else
728                 {
729                     if (key.IndexOf("_outside") > -1)
730                     {
731                         firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier == key.Substring(0, key.LastIndexOf("_outside")));
732                         if (firstOrDefault != null)
733                             return firstOrDefault.Value;
734                     }
735                 }
736             }
737             return "";
738         }
739 
740         public static string WebPostRequest(string url, string postData)
741         {
742             return CallWebRequest.Post(url, postData);
743         }
744         public static string WebGetRequest(string url)
745         {
746             return CallWebRequest.Get(url);
747         }
748 
749         #endregion
750 
751 
752         #region 参数转换方法
753         private static string ConvertClassIds(string classIds)
754         {
755             var list = classIds.Split(,);
756             StringBuilder sb = new StringBuilder("{\"class_id_list\": [");
757             foreach (var s in list)
758             {
759                 sb.Append("{\"classId\": \"" + s + "\"},");
760             }
761             if (list.Any())
762                 sb.Remove(sb.Length - 1, 1);
763 
764             sb.Append("]}");
765 
766             return sb.ToString();
767         }
768 
769         private static string ConvertLabIds(string labIds)
770         {
771             var list = labIds.Split(,);
772             StringBuilder sb = new StringBuilder("{\"lab_id_list\": [");
773             foreach (var s in list)
774             {
775                 sb.Append("{\"labId\": \"" + s + "\"},");
776             }
777             if (list.Any())
778                 sb.Remove(sb.Length - 1, 1);
779 
780             sb.Append("]}");
781 
782             return sb.ToString();
783         }
784 
785         private static string ConvertCardNos(string cardNos)
786         {
787             var list = cardNos.Split(,);
788             StringBuilder sb = new StringBuilder("{\"student_cardNos_list\": [");
789             foreach (var s in list)
790             {
791                 sb.Append("{\"stuCardNo\": \"" + s + "\"},");
792             }
793             if (list.Any())
794                 sb.Remove(sb.Length - 1, 1);
795 
796             sb.Append("]}");
797 
798             return sb.ToString();
799         }
800         #endregion
801 
802 
803 
804         /// <summary>
805         /// 设置公文已读
806         /// </summary>
807         /// <param name="beginTime"></param>
808         /// <param name="endTime"></param>
809         /// <param name="userId"></param>
810         /// <param name="currentPage"></param>
811         /// <param name="pageSize"></param>
812         /// <returns></returns>
813         public static Api_ToConfig<object> FlowService(string id)
814         {
815             var url = WebConfigManager.GetAppSettings("FlowService");
816             var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?Copyid=" + id, ""));
817             return data;
818         }
819 
820 
821         /// <summary>
822         ///获取OA工作流数据
823         /// </summary>
824         public static string getOAWorkFlowData(string userName, string userId)
825         {
826             var url = GetConfig("platform.application.oa.url") + WebConfigManager.GetAppSettings("OAWorkFlowData");
827             var data = CallWebRequest.Post(url, "&account=" + userName + "&userId=" + userId);
828             return data;
829 
830         }
831 
832         public static List<Api_Course> GetDreamClassCourse(string userId)
833         {
834             List<Api_Course> list = new List<Api_Course>();
835             list = CacheRedis.Cache.Get<List<Api_Course>>(RedisKey.DreamCourse + userId);
836             if (list != null && list.Count > 0)
837                 return list;
838 
839             var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getTeacherCourseInfo";
840             var result = Json.ToObject<ApiResult<Api_Course>>(CallWebRequest.Post(url, "&userId=" + userId));
841             if (result.state)
842                 list = result.data;
843             CacheRedis.Cache.Set(RedisKey.DreamCourse + userId, list, 30);//缓存30分钟失效
844             return list;
845         }
846 
847         /// <summary>
848         /// 用户信息
849         /// </summary>
850         /// <param name="userId"></param>
851         /// <returns></returns>
852         public static Api_User GetUserInfoByUserName(string userName)
853         {
854             var model = new Api_User();
855             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserName";
856             var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Post(url, "&userName=" + userName));
857             if (result.status == true && result.data != null)
858                 model = result.data;
859             return model;
860         }
861 
862         public static Api_User GetUserInfoByUserId(string userId)
863         {
864             var model = new Api_User();
865             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserId";
866             var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId));
867             if (result.status == true && result.data != null)
868                 model = result.data;
869             return model;
870         }
871 
872         public static Api_User GetUserByUserId(string userId)
873         {
874             var model = new Api_User();
875             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserByUserId";
876             var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId));
877             if (result.status == true && result.data != null)
878                 model = result.data;
879             return model;
880         }
881 
882 
883         public static ApiBase<string> UserExist(string userName)
884         {
885             ApiBase<string> result = new ApiBase<string>();
886             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserExists";
887             result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName));
888             return result;
889 
890         }
891         public static ApiBase<string> CheckUserPwd(string userName, string pwd)
892         {
893             ApiBase<string> result = new ApiBase<string>();
894             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserPsw";
895             result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&psw=" + pwd));
896             return result;
897 
898         }
899         public static ApiBase<Api_AnswerQuestion> GetAnswerQuestion(string userName)
900         {
901             ApiBase<Api_AnswerQuestion> result = new ApiBase<Api_AnswerQuestion>();
902             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/getSafetyByUserName";
903             result = Json.ToObject<ApiBase<Api_AnswerQuestion>>(CallWebRequest.Post(url, "&userName=" + userName));
904             return result;
905         }
906 
907         public static ApiBase<string> ResetUserPassword(string userName, string newPassWord)
908         {
909             ApiBase<string> result = new ApiBase<string>();
910             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/resetUserPasswordByUserName";
911             result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&newPassWord=" + newPassWord));
912             return result;
913         }
914         public static ApiBase<string> ChangeUserSafeAnswer(string userId, string answer1, string answer2, string answer3, string safeId)
915         {
916             ApiBase<string> result = new ApiBase<string>();
917             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/batchUpdageSafety";
918             result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{editor:\"" + userId + "\",safetyAnswerOne:\"" + answer1 + "\",safetyAnswerTwo:\"" + answer2 + "\",safetyAnswerThree:\"" + answer3 + "\",safetyId:" + safeId + "}]"));
919             return result;
920         }
921 
922         public static ApiBase<string> UpdateUserPhoto(string userId, string userPhoto)
923         {
924             ApiBase<string> result = new ApiBase<string>();
925             var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updataUserInfo";
926             result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{userId:\"" + userId + "\",userPhoto:\"" + userPhoto + "\"}]"));
927             return result;
928         }
929 
930         public static Api_DreamClassUserInfo GetDreamClassUser(string userId)
931         {
932             var model = new Api_DreamClassUserInfo();
933             //model = CacheRedis.Cache.Get<Api_DreamClassUserInfo>(RedisKey.DreamCourseUser + userId);
934             var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getUserInfo";
935             var result = Json.ToObject<ApiBase<Api_DreamClassUserInfo>>(CallWebRequest.Post(url, "&userId=" + userId));
936             if (result.state == true && result.data != null)
937             {
938                 model = result.data;
939                 //CacheRedis.Cache.Set(RedisKey.DreamCourseUser+userId,model);
940             }
941 
942             return model;
943         }
944 
945         public static List<Api_BitCourse> GetBitCourseList(string userName)
946         {
947             List<Api_BitCourse> list = new List<Api_BitCourse>();
948             list = CacheRedis.Cache.Get<List<Api_BitCourse>>(RedisKey.BitCourse + userName);
949             if (list != null && list.Count > 0)
950                 return list;
951             try
952             {
953                 var url = GetConfig("platform.system.szhjxpt.url", true) + "/Services/DtpServiceWJL.asmx/GetMyCourseByLoginName";
954                 var result = Json.ToObject<ApiConfig<Api_BitCourse>>(CallWebRequest.Post(url, "&loginName=" + userName));
955 
956                 if (result.success)
957                     list = result.datas;
958                 CacheRedis.Cache.Set(RedisKey.BitCourse + userName, list, 30);//缓存30分钟失效
959             }
960             catch (Exception exception)
961             {
962                 list = new List<Api_BitCourse>();
963                 Log.Error(exception.Message);
964             }
965 
966             return list;
967         }
968     }
View Code

 

C# WebRequest

标签:sign   次数   private   start   owa   转化   pac   begin   hid   

原文地址:https://www.cnblogs.com/DataBase-123/p/11011499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!