C# POST访问需要HTTP Digest Authentication认证资源的实现

来源:互联网 发布:收银系统怎么删除数据 编辑:程序博客网 时间:2024/06/04 17:47

http://blog.163.com/da7_1@126/blog/static/104072678201193024259807/


关于HTTP协议请看这篇博文

在你访问一个需要HTTP Digest Authentication的URL的时候,如果你没有提供用户名和密码,服务器就会返回401,如果你直接在浏览器中打开,浏览器会提示你输入用户名和密码;要在发送请求的时候添加HTTP Digest Authentication认证信息到请求中,有两种方法:

  • 一是在请求头中添加Authorization:
    Authorization: "Digest 用户名和密码的base64加密字符串"
  • 二是在url中添加用户名和密码:
    http://userName:password@XXX

除去最常用的GET,当使用需要账户密码访问的站点功能时(比如以http形式访问的短信网关)常常需要POST相应信息(无论它的消息格式是什么),下面是封装好的一个方法:

 
  1. public int PostRequest(string Url, string user, string pwd, string paramData, Encoding MsgEncode)
  2. {
  3. if (string.IsNullOrEmpty(Url))
  4. {
  5. throw new ArgumentNullException("Url");
  6. }
  7. if (MsgEncode == null)
  8. {
  9. throw new ArgumentNullException("MsgEncoding");
  10. }
  11. string username = user;
  12. string password = pwd;
  13. string usernamePassword = username + ":" + password;
  14. CredentialCache mycache = new CredentialCache();
  15. mycache.Add(new Uri(Url), "Digest"new NetworkCredential(username, password));
  16. Logger.INFO(GetType().ToString(), "PostRequest""POST HTTP请求,创建短信请求"string.Empty);
  17. HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(new Uri(Url));
  18. Request.Credentials = mycache;
  19. Request.Headers.Add("Authorization""Digest" + Convert.ToBase64String(MsgEncode.GetBytes(usernamePassword)));
  20. Request.Method = "POST";
  21. //Request.Timeout = 1000;
  22. Request.ContentType = "application/x-www-form-urlencoded";
  23. string temp_paramData = "json = " + System.Web.HttpUtility.UrlEncode(paramData);
  24. byte[] byteArray = MsgEncode.GetBytes(temp_paramData);
  25. Request.ContentLength = byteArray.Length;
  26. Stream newStream = Request.GetRequestStream();
  27. newStream.Write(byteArray, 0, byteArray.Length);
  28. newStream.Close();
  29. //string ret = string.Empty;
  30. Logger.INFO(GetType().ToString(), "PostRequest""POST HTTP请求,获取短信HTTP请求响应",string.Empty);
  31. HttpWebResponse response;
  32. try
  33. {
  34. response = (HttpWebResponse)Request.GetResponse();
  35. }
  36. catch (WebException ex)
  37. {
  38. response = (HttpWebResponse)ex.Response;
  39. }
  40. int ret = 0;
  41. ret = (int)response.StatusCode;
  42. Logger.INFO(GetType().ToString(), "PostRequest""POST HTTP请求,发送短信请求返回状态码", ret.ToString() + ParaHttpResult(ret));
  43. Stream stream = response.GetResponseStream();
  44. byte[] rsByte = new Byte[response.ContentLength];
  45. //StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
  46. //ret = sr.ReadToEnd();
  47. try
  48. {
  49. stream.Read(rsByte, 0, (int)response.ContentLength);
  50. Logger.INFO(GetType().ToString(), "PostRequest""POST HTTP请求,发送短信请求返回内容", System.Text.Encoding.UTF8.GetString(rsByte, 0, rsByte.Length).ToString());
  51. }
  52. catch (Exception ex)
  53. {
  54. Logger.ERROR(GetType().ToString(), "PostRequest""POST HTTP请求,发送短信请求返回内容异常", ex.ToString());
  55. }
  56. stream.Close();
  57. response.Close();
  58. return ret;
  59. }


第一个参数是接受http访问的url,第二第三参数分别是用户名密码,第四个参数是消息内容,第五个参数是消息内容的编码格式,关于认证的三种方式和C#相应的类可以查阅基于C#的http协议开发,该方法采用的是Digest摘要认证形式,而且消息体格式为json;关于http请求消息的写入和http响应的获取可以查看该方法的实现与MSDN结合看,这样会有一个比较全面的认识。

最后该方法的返回参数为http响应的状态码即200、401等,response.StatusCode是一个枚举,如果不进行转换获得的是 OK、NotFound 这样的名称。