当前位置:   article > 正文

C#中HttpWebRequest的用法详解_c# webrequest

c# webrequest

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 的情况下。

C# HttpWebRequest提交数据方式的基本内容就向你介绍到这里,希望对你了解和学习C# HttpWebRequest提交数据方式有所帮助。

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

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. byte[] postBytes = string.IsNullOrEmpty(strPostData) ? new byte[0] : Encoding.UTF8.GetBytes(strPostData);
  28. return HttpPost(strUrl, postBytes, cookieContainer, out strResult);
  29. }

post上传文件

/// <summary>
/// 发起Post文件请求(采用HttpWebRequest,支持传Cookie)
/// </summary>
/// <param name="strUrl">请求Url</param>
/// <param name="strFilePostName">上传文件的PostName</param>
/// <param name="strFilePath">上传文件路径</param>
/// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <param name="strResult">返回请求结果(如果请求失败,返回异常消息)</param>
/// <returns>返回:是否请求成功</returns>
public static bool HttpPostFile(string strUrl, string strFilePostName, string strFilePath, CookieContainer cookieContainer, out string strResult)
{
HttpWebRequest request = null;
FileStream fileStream = FileHelper.GetFileStream(strFilePath);

try
{
if (fileStream == null)
{
throw new FileNotFoundException();
}

request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Method = "POST";
request.KeepAlive = false;
request.Timeout = 30000;

if (cookieContainer != null)
{
request.CookieContainer = cookieContainer;
}

string boundary = string.Format("---------------------------{0}", DateTime.Now.Ticks.ToString("x"));

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",
boundary, strFilePostName, Path.GetFileName(strFilePath)));
byte[] footer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary));

request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
request.ContentLength = header.Length + fileStream.Length + footer.Length;

using (Stream reqStream = request.GetRequestStream())
{
// 写入分割线及数据信息
reqStream.Write(header, 0, header.Length);

// 写入文件
FileHelper.WriteFile(reqStream, fileStream);

// 写入尾部
reqStream.Write(footer, 0, footer.Length);
}

strResult = GetResponseResult(request, cookieContainer);
}
catch (Exception ex)
{
strResult = ex.Message;
return false;
}
finally
{
if (request != null)
{
request.Abort();
}
if (fileStream != null)
{
fileStream.Close();
}
}

return true;
}


/// <summary>
/// 获取请求结果字符串
/// </summary>
/// <param name="request">请求对象(发起请求之后)</param>
/// <param name="cookieContainer">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns>返回请求结果字符串</returns>
private static string GetResponseResult(HttpWebRequest request, CookieContainer cookieContainer = null)
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
using (Stream rspStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
 

 

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. StringBuilder requestBody = new StringBuilder("");
  12. Encoding encoding = Encoding.GetEncoding("utf-8");
  13. byte[] data = encoding.GetBytes(requestBody.ToString());
  14. // Http Request的设置
  15. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  16. request.Headers.Set("Authorization", oauthHeader.ToString());
  17. //request.Headers.Add("Authorization", authorization);
  18. request.ContentType = "application/atom+xml";
  19. request.Method = "GET";
 

 

C#通过WebClient/HttpWebRequest实现http的post/get方法

1.POST方法(httpWebRequest)

  1. //body是要传递的参数,格式"roleId=1&uid=2"
  2. //post的cotentType填写:"application/x-www-form-urlencoded"
  3. //soap填写:"text/xml; charset=utf-8"
  4. public static string PostHttp(string url, string body, string contentType)
  5. {
  6. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
  7. httpWebRequest.ContentType = contentType;
  8. httpWebRequest.Method = "POST";
  9. httpWebRequest.Timeout = 20000;
  10. byte[] btBodys = Encoding.UTF8.GetBytes(body);
  11. httpWebRequest.ContentLength = btBodys.Length;
  12. httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
  13. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  14. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
  15. string responseContent = streamReader.ReadToEnd();
  16. httpWebResponse.Close();
  17. streamReader.Close();
  18. httpWebRequest.Abort();
  19. httpWebResponse.Close();
  20. return responseContent;
  21. }
  22. POST方法(httpWebRequest)
 


2.POST方法(WebClient)

 
  1. // <summary>
  2. /// 通过WebClient类Post数据到远程地址,需要Basic认证;
  3. /// 调用端自己处理异常
  4. /// </summary>
  5. /// <param name="uri"></param>
  6. /// <param name="paramStr">name=张三&age=20</param>
  7. /// <param name="encoding">请先确认目标网页的编码方式</param>
  8. /// <param name="username"></param>
  9. /// <param name="password"></param>
  10. /// <returns></returns>
  11. public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
  12. {
  13. if (encoding == null)
  14. encoding = Encoding.UTF8;
  15. string result = string.Empty;
  16. WebClient wc = new WebClient();
  17. // 采取POST方式必须加的Header
  18. wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  19. byte[] postData = encoding.GetBytes(paramStr);
  20. if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
  21. {
  22. wc.Credentials = GetCredentialCache(uri, username, password);
  23. wc.Headers.Add("Authorization", GetAuthorization(username, password));
  24. }
  25. byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
  26. return encoding.GetString(responseData);// 解码
  27. }
  28. POST方法(WebClient)
 

3.Get方法(httpWebRequest)

 
  1. public static string GetHttp(string url, HttpContext httpContext)
  2. {
  3. string queryString = "?";
  4. foreach (string key in httpContext.Request.QueryString.AllKeys)
  5. {
  6. queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
  7. }
  8. queryString = queryString.Substring(0, queryString.Length - 1);
  9. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
  10. httpWebRequest.ContentType = "application/json";
  11. httpWebRequest.Method = "GET";
  12. httpWebRequest.Timeout = 20000;
  13. //byte[] btBodys = Encoding.UTF8.GetBytes(body);
  14. //httpWebRequest.ContentLength = btBodys.Length;
  15. //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
  16. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  17. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
  18. string responseContent = streamReader.ReadToEnd();
  19. httpWebResponse.Close();
  20. streamReader.Close();
  21. return responseContent;
  22. }
  23. Get方法(HttpWebRequest)
 

4.basic验证的WebRequest/WebResponse

 
  1. /// <summary>
  2. /// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
  3. /// 调用端自己处理异常
  4. /// </summary>
  5. /// <param name="uri"></param>
  6. /// <param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>
  7. /// <param name="encoding">如果不知道具体的编码,传入null</param>
  8. /// <param name="username"></param>
  9. /// <param name="password"></param>
  10. /// <returns></returns>
  11. public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
  12. {
  13. string result = string.Empty;
  14. WebRequest request = WebRequest.Create(new Uri(uri));
  15. if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
  16. {
  17. request.Credentials = GetCredentialCache(uri, username, password);
  18. request.Headers.Add("Authorization", GetAuthorization(username, password));
  19. }
  20. if (timeout > 0)
  21. request.Timeout = timeout;
  22. WebResponse response = request.GetResponse();
  23. Stream stream = response.GetResponseStream();
  24. StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
  25. result = sr.ReadToEnd();
  26. sr.Close();
  27. stream.Close();
  28. return result;
  29. }
  30. #region # 生成 Http Basic 访问凭证 #
  31. private static CredentialCache GetCredentialCache(string uri, string username, string password)
  32. {
  33. string authorization = string.Format("{0}:{1}", username, password);
  34. CredentialCache credCache = new CredentialCache();
  35. credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
  36. return credCache;
  37. }
  38. private static string GetAuthorization(string username, string password)
  39. {
  40. string authorization = string.Format("{0}:{1}", username, password);
  41. return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
  42. }
  43. #endregion
  44. basic验证的WebRequest/WebResponse

C#语言写的关于HttpWebRequest 类的使用方法

http://www.jb51.net/article/57156.htm

 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. namespace HttpWeb
  7. {
  8.     /// <summary>
  9.     ///  Http操作类
  10.     /// </summary>
  11.     public static class httptest
  12.     {
  13.         /// <summary>
  14.         ///  获取网址HTML
  15.         /// </summary>
  16.         /// <param name="URL">网址 </param>
  17.         /// <returns> </returns>
  18.         public static string GetHtml(string URL)
  19.         {
  20.             WebRequest wrt;
  21.             wrt = WebRequest.Create(URL);
  22.             wrt.Credentials = CredentialCache.DefaultCredentials;
  23.             WebResponse wrp;
  24.             wrp = wrt.GetResponse();
  25.             string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
  26.             try
  27.             {
  28.                 wrt.GetResponse().Close();
  29.             }
  30.             catch (WebException ex)
  31.             {
  32.                 throw ex;
  33.             }
  34.             return reader;
  35.         }
  36.         /// <summary>
  37.         /// 获取网站cookie
  38.         /// </summary>
  39.         /// <param name="URL">网址 </param>
  40.         /// <param name="cookie">cookie </param>
  41.         /// <returns> </returns>
  42.         public static string GetHtml(string URL, out string cookie)
  43.         {
  44.             WebRequest wrt;
  45.             wrt = WebRequest.Create(URL);
  46.             wrt.Credentials = CredentialCache.DefaultCredentials;
  47.             WebResponse wrp;
  48.             wrp = wrt.GetResponse();
  49.             string html = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
  50.             try
  51.             {
  52.                 wrt.GetResponse().Close();
  53.             }
  54.             catch (WebException ex)
  55.             {
  56.                 throw ex;
  57.             }
  58.             cookie = wrp.Headers.Get("Set-Cookie");
  59.             return html;
  60.         }
  61.         public static string GetHtml(string URL, string postData, string cookie, out string header, string server)
  62.         {
  63.             return GetHtml(server, URL, postData, cookie, out header);
  64.         }
  65.         public static string GetHtml(string server, string URL, string postData, string cookie, out string header)
  66.         {
  67.             byte[] byteRequest = Encoding.GetEncoding("gb2312").GetBytes(postData);
  68.             return GetHtml(server, URL, byteRequest, cookie, out header);
  69.         }
  70.         public static string GetHtml(string server, string URL, byte[] byteRequest, string cookie, out string header)
  71.         {
  72.             byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header);
  73.             Stream getStream = new MemoryStream(bytes);
  74.             StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
  75.             string getString = streamReader.ReadToEnd();
  76.             streamReader.Close();
  77.             getStream.Close();
  78.             return getString;
  79.         }
  80.         /// <summary>
  81.         /// Post模式浏览
  82.         /// </summary>
  83.         /// <param name="server">服务器地址 </param>
  84.         /// <param name="URL">网址 </param>
  85.         /// <param name="byteRequest"></param>
  86.         /// <param name="cookie">cookie </param>
  87.         /// <param name="header">句柄 </param>
  88.         /// <returns> </returns>
  89.         public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header)
  90.         {
  91.             long contentLength;
  92.             HttpWebRequest httpWebRequest;
  93.             HttpWebResponse webResponse;
  94.             Stream getStream;
  95.             httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
  96.             CookieContainer co = new CookieContainer();
  97.             co.SetCookies(new Uri(server), cookie);
  98.             httpWebRequest.CookieContainer = co;
  99.             httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  100.             httpWebRequest.Accept =
  101.                 "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
  102.             httpWebRequest.Referer = server;
  103.             httpWebRequest.UserAgent =
  104.                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
  105.             httpWebRequest.Method = "Post";
  106.             httpWebRequest.ContentLength = byteRequest.Length;
  107.             Stream stream;
  108.             stream = httpWebRequest.GetRequestStream();
  109.             stream.Write(byteRequest, 0, byteRequest.Length);
  110.             stream.Close();
  111.             webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  112.             header = webResponse.Headers.ToString();
  113.             getStream = webResponse.GetResponseStream();
  114.             contentLength = webResponse.ContentLength;
  115.             byte[] outBytes = new byte[contentLength];
  116.             outBytes = ReadFully(getStream);
  117.             getStream.Close();
  118.             return outBytes;
  119.         }
  120.         public static byte[] ReadFully(Stream stream)
  121.         {
  122.             byte[] buffer = new byte[128];
  123.             using (MemoryStream ms = new MemoryStream())
  124.             {
  125.                 while (true)
  126.                 {
  127.                     int read = stream.Read(buffer, 0, buffer.Length);
  128.                     if (read <= 0)
  129.                         return ms.ToArray();
  130.                     ms.Write(buffer, 0, read);
  131.                 }
  132.             }
  133.         }
  134.         /// <summary>
  135.         /// Get模式
  136.         /// </summary>
  137.         /// <param name="URL">网址 </param>
  138.         /// <param name="cookie">cookies </param>
  139.         /// <param name="header">句柄 </param>
  140.         /// <param name="server">服务器 </param>
  141.         /// <param name="val">服务器 </param>
  142.         /// <returns> </returns>
  143.         public static string GetHtml(string URL, string cookie, out string header, string server)
  144.         {
  145.             return GetHtml(URL, cookie, out header, server, "");
  146.         }
  147.         /// <summary>
  148.         /// Get模式浏览
  149.         /// </summary>
  150.         /// <param name="URL">Get网址 </param>
  151.         /// <param name="cookie">cookie </param>
  152.         /// <param name="header">句柄 </param>
  153.         /// <param name="server">服务器地址 </param>
  154.         /// <param name="val"> </param>
  155.         /// <returns> </returns>
  156.         public static string GetHtml(string URL, string cookie, out string header, string server, string val)
  157.         {
  158.             HttpWebRequest httpWebRequest;
  159.             HttpWebResponse webResponse;
  160.             Stream getStream;
  161.             StreamReader streamReader;
  162.             string getString = "";
  163.             httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
  164.             httpWebRequest.Accept = "*/*";
  165.             httpWebRequest.Referer = server;
  166.             CookieContainer co = new CookieContainer();
  167.             co.SetCookies(new Uri(server), cookie);
  168.             httpWebRequest.CookieContainer = co;
  169.             httpWebRequest.UserAgent =
  170.                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
  171.             httpWebRequest.Method = "GET";
  172.             webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  173.             header = webResponse.Headers.ToString();
  174.             getStream = webResponse.GetResponseStream();
  175.             streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
  176.             getString = streamReader.ReadToEnd();
  177.             streamReader.Close();
  178.             getStream.Close();
  179.             return getString;
  180.         }
  181.    }
  182. }
 

 有空查看:

 
  1. /// <summary>
  2. /// 作用描述: WebRequest操作类
  3. /// </summary>
  4. public static class CallWebRequest
  5. {
  6. /// <summary>
  7. /// 通过GET请求获取数据
  8. /// </summary>
  9. /// <param name="url"></param>
  10. /// <returns></returns>
  11. public static string Get(string url)
  12. {
  13. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  14. //每次请求绕过代理,解决第一次调用慢的问题
  15. request.Proxy = null;
  16. //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
  17. ServicePoint currentServicePoint = request.ServicePoint;
  18. currentServicePoint.ConnectionLimit = 1000;
  19. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  20. string str;
  21. using (Stream responseStream = response.GetResponseStream())
  22. {
  23. Encoding encode = Encoding.GetEncoding("utf-8");
  24. StreamReader reader = new StreamReader(responseStream, encode);
  25. str = reader.ReadToEnd();
  26. }
  27. response.Close();
  28. response = null;
  29. request.Abort();
  30. request = null;
  31. return str;
  32. }
  33. /// <summary>
  34. /// 通过POST请求传递数据
  35. /// </summary>
  36. /// <param name="url"></param>
  37. /// <param name="postData"></param>
  38. /// <returns></returns>
  39. public static string Post(string url, string postData)
  40. {
  41. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  42. //将发送数据转换为二进制格式
  43. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  44. //要POST的数据大于1024字节的时候, 浏览器并不会直接就发起POST请求, 而是会分为俩步:
  45. //1. 发送一个请求, 包含一个Expect:100-continue, 询问Server使用愿意接受数据
  46. //2. 接收到Server返回的100-continue应答以后, 才把数据POST给Server
  47. //直接关闭第一步验证
  48. request.ServicePoint.Expect100Continue = false;
  49. //是否使用Nagle:不使用,提高效率
  50. request.ServicePoint.UseNagleAlgorithm = false;
  51. //设置最大连接数
  52. request.ServicePoint.ConnectionLimit = 65500;
  53. //指定压缩方法
  54. //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
  55. request.KeepAlive = false;
  56. //request.ContentType = "application/json";
  57. request.ContentType = "application/x-www-form-urlencoded";
  58. request.Method = "POST";
  59. request.Timeout = 20000;
  60. request.ContentLength = byteArray.Length;
  61. //关闭缓存
  62. request.AllowWriteStreamBuffering = false;
  63. //每次请求绕过代理,解决第一次调用慢的问题
  64. request.Proxy = null;
  65. //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
  66. ServicePoint currentServicePoint = request.ServicePoint;
  67. Stream dataStream = request.GetRequestStream();
  68. dataStream.Write(byteArray, 0, byteArray.Length);
  69. dataStream.Close();
  70. WebResponse response = request.GetResponse();
  71. //获取服务器返回的数据流
  72. dataStream = response.GetResponseStream();
  73. StreamReader reader = new StreamReader(dataStream);
  74. string responseFromServer = reader.ReadToEnd();
  75. reader.Close();
  76. dataStream.Close();
  77. request.Abort();
  78. response.Close();
  79. reader.Dispose();
  80. dataStream.Dispose();
  81. return responseFromServer;
  82. }
  83. }
 
  1. /// <summary>
  2. /// 用于外部接口调用封装
  3. /// </summary>
  4. public static class ApiInterface
  5. {
  6. /// <summary>
  7. ///验证密码是否正确
  8. /// </summary>
  9. public static Api_ToConfig<object> checkPwd(int userId, string old)
  10. {
  11. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkPwd";
  12. var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId, "&oldPwd=" + old));
  13. //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}"));
  14. return data;
  15. }
  16. /// <summary>
  17. ///
  18. /// </summary>
  19. public static Api_ToConfig<object> UpdatePassword(int userId, string pwd, string old)
  20. {
  21. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updatePwd";
  22. var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId + "&oldPwd=" + old, "&newPwd=" + pwd));
  23. //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}"));
  24. return data;
  25. }
  26. private static DateTime GetTime(string timeStamp)
  27. {
  28. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  29. long lTime = long.Parse(timeStamp + "0000");
  30. TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
  31. }
  32. #region 公共方法
  33. /// <summary>
  34. /// 配置文件key
  35. /// </summary>
  36. /// <param name="key"></param>
  37. /// <param name="isOutKey"></param>
  38. /// <returns></returns>
  39. public static string GetConfig(string key, bool isOutKey = false)
  40. {
  41. // CacheRedis.Cache.RemoveObject(RedisKey.ConfigList);
  42. var data = CacheRedis.Cache.Get<Api_BaseToConfig<Api_Config>>(RedisKey.ConfigList);
  43. // var data = new Api_BaseToConfig<Api_Config>();
  44. if (data == null)
  45. {
  46. string dataCenterUrl = WebConfigManager.GetAppSettings("DataCenterUrl");
  47. string configurationInfoListByFilter = WebConfigManager.GetAppSettings("ConfigurationInfoListByFilter");
  48. string systemCoding = WebConfigManager.GetAppSettings("SystemCoding");
  49. string nodeIdentifier = WebConfigManager.GetAppSettings("NodeIdentifier");
  50. string para = "systemIdf=" + systemCoding + "&nodeIdf=" + nodeIdentifier + "";
  51. //string para = "{\"systemIdf\":\"" + systemCoding + "\",\"nodeIdf\":\"" + nodeIdentifier + "\"}";
  52. string result = CallWebRequest.Post(dataCenterUrl + "/rest" + configurationInfoListByFilter, para);
  53. data =
  54. Json.ToObject<Api_BaseToConfig<Api_Config>>(result);
  55. CacheRedis.Cache.Set(RedisKey.ConfigList, data);
  56. }
  57. if (data.Status)
  58. {
  59. if (isOutKey && ConfigServer.IsOutside())
  60. {
  61. key += "_outside";
  62. }
  63. key = key.ToLower();
  64. var firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier.ToLower() == key);
  65. if (firstOrDefault != null)
  66. {
  67. return firstOrDefault.Value;
  68. }
  69. else
  70. {
  71. if (key.IndexOf("_outside") > -1)
  72. {
  73. firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier == key.Substring(0, key.LastIndexOf("_outside")));
  74. if (firstOrDefault != null)
  75. return firstOrDefault.Value;
  76. }
  77. }
  78. }
  79. return "";
  80. }
  81. public static string WebPostRequest(string url, string postData)
  82. {
  83. return CallWebRequest.Post(url, postData);
  84. }
  85. public static string WebGetRequest(string url)
  86. {
  87. return CallWebRequest.Get(url);
  88. }
  89. #endregion
  90. #region 参数转换方法
  91. private static string ConvertClassIds(string classIds)
  92. {
  93. var list = classIds.Split(',');
  94. StringBuilder sb = new StringBuilder("{\"class_id_list\": [");
  95. foreach (var s in list)
  96. {
  97. sb.Append("{\"classId\": \"" + s + "\"},");
  98. }
  99. if (list.Any())
  100. sb.Remove(sb.Length - 1, 1);
  101. sb.Append("]}");
  102. return sb.ToString();
  103. }
  104. private static string ConvertLabIds(string labIds)
  105. {
  106. var list = labIds.Split(',');
  107. StringBuilder sb = new StringBuilder("{\"lab_id_list\": [");
  108. foreach (var s in list)
  109. {
  110. sb.Append("{\"labId\": \"" + s + "\"},");
  111. }
  112. if (list.Any())
  113. sb.Remove(sb.Length - 1, 1);
  114. sb.Append("]}");
  115. return sb.ToString();
  116. }
  117. private static string ConvertCardNos(string cardNos)
  118. {
  119. var list = cardNos.Split(',');
  120. StringBuilder sb = new StringBuilder("{\"student_cardNos_list\": [");
  121. foreach (var s in list)
  122. {
  123. sb.Append("{\"stuCardNo\": \"" + s + "\"},");
  124. }
  125. if (list.Any())
  126. sb.Remove(sb.Length - 1, 1);
  127. sb.Append("]}");
  128. return sb.ToString();
  129. }
  130. #endregion
  131. /// <summary>
  132. /// 设置公文已读
  133. /// </summary>
  134. /// <param name="beginTime"></param>
  135. /// <param name="endTime"></param>
  136. /// <param name="userId"></param>
  137. /// <param name="currentPage"></param>
  138. /// <param name="pageSize"></param>
  139. /// <returns></returns>
  140. public static Api_ToConfig<object> FlowService(string id)
  141. {
  142. var url = WebConfigManager.GetAppSettings("FlowService");
  143. var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?Copyid=" + id, ""));
  144. return data;
  145. }
  146. /// <summary>
  147. ///获取OA工作流数据
  148. /// </summary>
  149. public static string getOAWorkFlowData(string userName, string userId)
  150. {
  151. var url = GetConfig("platform.application.oa.url") + WebConfigManager.GetAppSettings("OAWorkFlowData");
  152. var data = CallWebRequest.Post(url, "&account=" + userName + "&userId=" + userId);
  153. return data;
  154. }
  155. public static List<Api_Course> GetDreamClassCourse(string userId)
  156. {
  157. List<Api_Course> list = new List<Api_Course>();
  158. list = CacheRedis.Cache.Get<List<Api_Course>>(RedisKey.DreamCourse + userId);
  159. if (list != null && list.Count > 0)
  160. return list;
  161. var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getTeacherCourseInfo";
  162. var result = Json.ToObject<ApiResult<Api_Course>>(CallWebRequest.Post(url, "&userId=" + userId));
  163. if (result.state)
  164. list = result.data;
  165. CacheRedis.Cache.Set(RedisKey.DreamCourse + userId, list, 30);//缓存30分钟失效
  166. return list;
  167. }
  168. /// <summary>
  169. /// 用户信息
  170. /// </summary>
  171. /// <param name="userId"></param>
  172. /// <returns></returns>
  173. public static Api_User GetUserInfoByUserName(string userName)
  174. {
  175. var model = new Api_User();
  176. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserName";
  177. var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Post(url, "&userName=" + userName));
  178. if (result.status == true && result.data != null)
  179. model = result.data;
  180. return model;
  181. }
  182. public static Api_User GetUserInfoByUserId(string userId)
  183. {
  184. var model = new Api_User();
  185. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserId";
  186. var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId));
  187. if (result.status == true && result.data != null)
  188. model = result.data;
  189. return model;
  190. }
  191. public static Api_User GetUserByUserId(string userId)
  192. {
  193. var model = new Api_User();
  194. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserByUserId";
  195. var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId));
  196. if (result.status == true && result.data != null)
  197. model = result.data;
  198. return model;
  199. }
  200. public static ApiBase<string> UserExist(string userName)
  201. {
  202. ApiBase<string> result = new ApiBase<string>();
  203. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserExists";
  204. result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName));
  205. return result;
  206. }
  207. public static ApiBase<string> CheckUserPwd(string userName, string pwd)
  208. {
  209. ApiBase<string> result = new ApiBase<string>();
  210. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserPsw";
  211. result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&psw=" + pwd));
  212. return result;
  213. }
  214. public static ApiBase<Api_AnswerQuestion> GetAnswerQuestion(string userName)
  215. {
  216. ApiBase<Api_AnswerQuestion> result = new ApiBase<Api_AnswerQuestion>();
  217. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/getSafetyByUserName";
  218. result = Json.ToObject<ApiBase<Api_AnswerQuestion>>(CallWebRequest.Post(url, "&userName=" + userName));
  219. return result;
  220. }
  221. public static ApiBase<string> ResetUserPassword(string userName, string newPassWord)
  222. {
  223. ApiBase<string> result = new ApiBase<string>();
  224. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/resetUserPasswordByUserName";
  225. result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&newPassWord=" + newPassWord));
  226. return result;
  227. }
  228. public static ApiBase<string> ChangeUserSafeAnswer(string userId, string answer1, string answer2, string answer3, string safeId)
  229. {
  230. ApiBase<string> result = new ApiBase<string>();
  231. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/batchUpdageSafety";
  232. result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{editor:\"" + userId + "\",safetyAnswerOne:\"" + answer1 + "\",safetyAnswerTwo:\"" + answer2 + "\",safetyAnswerThree:\"" + answer3 + "\",safetyId:" + safeId + "}]"));
  233. return result;
  234. }
  235. public static ApiBase<string> UpdateUserPhoto(string userId, string userPhoto)
  236. {
  237. ApiBase<string> result = new ApiBase<string>();
  238. var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updataUserInfo";
  239. result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{userId:\"" + userId + "\",userPhoto:\"" + userPhoto + "\"}]"));
  240. return result;
  241. }
  242. public static Api_DreamClassUserInfo GetDreamClassUser(string userId)
  243. {
  244. var model = new Api_DreamClassUserInfo();
  245. //model = CacheRedis.Cache.Get<Api_DreamClassUserInfo>(RedisKey.DreamCourseUser + userId);
  246. var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getUserInfo";
  247. var result = Json.ToObject<ApiBase<Api_DreamClassUserInfo>>(CallWebRequest.Post(url, "&userId=" + userId));
  248. if (result.state == true && result.data != null)
  249. {
  250. model = result.data;
  251. //CacheRedis.Cache.Set(RedisKey.DreamCourseUser+userId,model);
  252. }
  253. return model;
  254. }
  255. public static List<Api_BitCourse> GetBitCourseList(string userName)
  256. {
  257. List<Api_BitCourse> list = new List<Api_BitCourse>();
  258. list = CacheRedis.Cache.Get<List<Api_BitCourse>>(RedisKey.BitCourse + userName);
  259. if (list != null && list.Count > 0)
  260. return list;
  261. try
  262. {
  263. var url = GetConfig("platform.system.szhjxpt.url", true) + "/Services/DtpServiceWJL.asmx/GetMyCourseByLoginName";
  264. var result = Json.ToObject<ApiConfig<Api_BitCourse>>(CallWebRequest.Post(url, "&loginName=" + userName));
  265. if (result.success)
  266. list = result.datas;
  267. CacheRedis.Cache.Set(RedisKey.BitCourse + userName, list, 30);//缓存30分钟失效
  268. }
  269. catch (Exception exception)
  270. {
  271. list = new List<Api_BitCourse>();
  272. Log.Error(exception.Message);
  273. }
  274. return list;
  275. }
  276. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/748408
推荐阅读
相关标签
  

闽ICP备14008679号