[C#] TestHttpPost(测试Http的POST方法)发布v1.2.1版,办理了部分网站无法打开的标题、忽略HTTPS证书查抄

[复制链接]
发表于 2025-9-19 10:15:30 | 显示全部楼层 |阅读模式
作者: zyl910
  近来有读者反馈“部分网站打不开”。于是我修正了这一标题,发布了v1.2.1版。
一、变更分析

v1.2.1的变更分析——

  • 办理了部分网站无法打开的标题. 改进 TLS 的版本兼容性.
  • 忽略HTTPS证书查抄, 用于支持证书无效的网站.
二、使用先容

用法与先前版本类似.

三、全部代码

窗口的代码(FrmTestHttpPost.cs)——
  1. ////////////////////////////////////////////////////////////
  2. // FrmTestHttpPost.cs: 测试Http的POST方法.
  3. // Author: zyl910
  4. // Blog: http://www.cnblogs.com/zyl910
  5. // URL: http://www.cnblogs.com/zyl910/archive/2012/09/19/TestHttpPost.html
  6. // Version: V1.2.1
  7. // Updata: 2025-07-15
  8. //
  9. ////////////////////////////////////////////////////////////
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Data;
  14. using System.Drawing;
  15. using System.IO;
  16. using System.IO.Pipes;
  17. using System.Net;
  18. using System.Net.Cache;
  19. using System.Net.Security;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using System.Windows.Forms;
  24. namespace TestHttpPost
  25. {
  26.     public partial class FrmTestHttpPost : Form
  27.     {
  28.         private EncodingInfo[] _Encodings = null;   // 编码集合.
  29.         private Encoding _ResEncoding = null;   // 回应的编码.
  30.         private bool _OutputFileAllow = false; // 允许输出文件.
  31.         private string _OutputFilePath = null; // 输出文件的路径.
  32.         private string[] _HeaderLines = null; // 请求头的行列表.
  33.         public FrmTestHttpPost()
  34.         {
  35.             int securityProtocol = 16368; // SSLv3 ~ TSLv1.3. 48 + 192 + 768 + 3072 + 12288 = 16368
  36.             ServicePointManager.SecurityProtocol = (SecurityProtocolType)securityProtocol;
  37.             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate {
  38.                 return true;//https请求 忽略证书,可以直接访问
  39.             });
  40.             InitializeComponent();
  41.         }
  42.         /// <summary>
  43.         /// 根据BodyName创建Encoding对象。
  44.         /// </summary>
  45.         /// <param name="bodyname">与邮件代理正文标记一起使用的当前编码的名称。</param>
  46.         /// <returns>返回Encoding对象。若没有匹配的BodyName,便返回null。</returns>
  47.         public static Encoding Encoding_FromBodyName(string bodyname)
  48.         {
  49.             if (string.IsNullOrEmpty(bodyname)) return null;
  50.             try
  51.             {
  52.                 foreach (EncodingInfo ei in Encoding.GetEncodings())
  53.                 {
  54.                     Encoding e = ei.GetEncoding();
  55.                     if (0 == string.Compare(bodyname, e.BodyName, true))
  56.                     {
  57.                         return e;
  58.                     }
  59.                 }
  60.             }
  61.             catch
  62.             {
  63.             }
  64.             return null;
  65.         }
  66.         /// <summary>
  67.         /// 输出日志日志文本.
  68.         /// </summary>
  69.         /// <param name="s">日志日志文本</param>
  70.         private void OutLog(string s)
  71.         {
  72.             txtLog.Invoke(new Action<string>(p =>
  73.             {
  74.                 txtLog.AppendText(p + Environment.NewLine);
  75.                 txtLog.ScrollToCaret();
  76.             }), s);
  77.         }
  78.         private void OutLog(string format, params object[] args)
  79.         {
  80.             OutLog(string.Format(format, args));
  81.         }
  82.         private void HttpReq(Encoding myEncoding, string sMode, string sUrl, string sContentType, string sPostData, bool bVerbose)
  83.         {
  84.             HttpWebRequest req;
  85.             // == main ==
  86.             if (bVerbose) OutLog(string.Format("{3}: {0} {1} {2}", sMode, sUrl, sPostData, DateTime.Now.ToString("g")));
  87.             try
  88.             {
  89.                 bool showRequestHeader = false;
  90.                 // init
  91.                 req = HttpWebRequest.Create(sMode == "GET" ? sUrl + sPostData : sUrl) as HttpWebRequest;
  92.                 req.Method = sMode;
  93.                 req.Accept = "*/*";
  94.                 req.KeepAlive = false;
  95.                 req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
  96.                 string[] headerLines = _HeaderLines;
  97.                 if (null != headerLines && headerLines.Length > 0) {
  98.                     var headers = req.Headers;
  99.                     // Set.
  100.                     showRequestHeader = true;
  101.                     foreach(string line in headerLines) {
  102.                         if (string.IsNullOrEmpty(line)) continue;
  103.                         int pos = line.IndexOf(':');
  104.                         if (pos <= 0) continue;
  105.                         string key = line.Substring(0, pos).Trim();
  106.                         string value = line.Substring(pos + 1).Trim();
  107.                         if (string.IsNullOrEmpty(key)) continue;
  108.                         headers[key] = value;
  109.                     }
  110.                 }
  111.                 if (0 == string.Compare("POST", sMode))
  112.                 {
  113.                     byte[] bufPost = myEncoding.GetBytes(sPostData);
  114.                     req.ContentType = sContentType;
  115.                     req.ContentLength = bufPost.Length;
  116.                     Stream newStream = req.GetRequestStream();
  117.                     newStream.Write(bufPost, 0, bufPost.Length);
  118.                     newStream.Close();
  119.                 }
  120.                 if (showRequestHeader) {
  121.                     var headers = req.Headers;
  122.                     // Output RequestHeader
  123.                     OutLog(".\t#RequestHeader:");
  124.                     for (int i = 0; i < headers.Count; ++i) {
  125.                         OutLog("[{2}] {0}:\t{1}", headers.Keys[i], headers[i], i);
  126.                     }
  127.                 }
  128.                 // Response
  129.                 HttpWebResponse res = req.GetResponse() as HttpWebResponse;
  130.                 try
  131.                 {
  132.                     if (bVerbose)
  133.                     {
  134.                         OutLog("Response.ContentLength:\t{0}", res.ContentLength);
  135.                         OutLog("Response.ContentType:\t{0}", res.ContentType);
  136.                         OutLog("Response.CharacterSet:\t{0}", res.CharacterSet);
  137.                         OutLog("Response.ContentEncoding:\t{0}", res.ContentEncoding);
  138.                         OutLog("Response.IsFromCache:\t{0}", res.IsFromCache);
  139.                         OutLog("Response.IsMutuallyAuthenticated:\t{0}", res.IsMutuallyAuthenticated);
  140.                         OutLog("Response.LastModified:\t{0}", res.LastModified);
  141.                         OutLog("Response.Method:\t{0}", res.Method);
  142.                         OutLog("Response.ProtocolVersion:\t{0}", res.ProtocolVersion);
  143.                         OutLog("Response.ResponseUri:\t{0}", res.ResponseUri);
  144.                         OutLog("Response.Server:\t{0}", res.Server);
  145.                         OutLog("Response.StatusCode:\t{0}\t# {1}", res.StatusCode, (int)res.StatusCode);
  146.                         OutLog("Response.StatusDescription:\t{0}", res.StatusDescription);
  147.                         // header
  148.                         OutLog(".\t#ResponseHeader:");  // 头.
  149.                         for (int i = 0; i < res.Headers.Count; ++i)
  150.                         {
  151.                             OutLog("[{2}] {0}:\t{1}", res.Headers.Keys[i], res.Headers[i], i);
  152.                         }
  153.                     }
  154.                     // 找到合适的编码
  155.                     Encoding encoding = null;
  156.                     //encoding = Encoding_FromBodyName(res.CharacterSet);        // 后来发现主体部分的字符集与Response.CharacterSet不同.
  157.                     //if (null == encoding) encoding = myEncoding;
  158.                     encoding = _ResEncoding;
  159.                     System.Diagnostics.Debug.WriteLine(encoding);
  160.                     // body
  161.                     if (bVerbose) OutLog(".\t#Body:");    // 主体.
  162.                     using (Stream resStreamRaw = res.GetResponseStream())
  163.                     {
  164.                         Stream resStream = resStreamRaw;
  165.                         if (_OutputFileAllow) {
  166.                             MemoryStream memoryStream = new MemoryStream();
  167.                             resStreamRaw.CopyTo(memoryStream);
  168.                             OutLog(string.Format("Byte size: {0} // 0x{0:X}", memoryStream.Length));
  169.                             if (!string.IsNullOrEmpty(_OutputFilePath)) {
  170.                                 string fullPath = Path.GetFullPath(_OutputFilePath);
  171.                                 memoryStream.Position = 0;
  172.                                 try {
  173.                                     File.WriteAllBytes(fullPath, memoryStream.GetBuffer());
  174.                                     OutLog(string.Format("Output file OK. {0}", fullPath));
  175.                                 } catch (Exception ex1) {
  176.                                     OutLog(string.Format("Output file fail! {0}", fullPath));
  177.                                     OutLog(ex1.ToString());
  178.                                 }
  179.                             }
  180.                             // next.
  181.                             memoryStream.Position = 0;
  182.                             resStream = memoryStream;
  183.                         }
  184.                         using (StreamReader resStreamReader = new StreamReader(resStream, encoding))
  185.                         {
  186.                             OutLog(resStreamReader.ReadToEnd());
  187.                         }
  188.                     }
  189.                     if (bVerbose) OutLog(".\t#OK.");  // 成功.
  190.                 }
  191.                 finally
  192.                 {
  193.                     res.Close();
  194.                 }
  195.             }
  196.             catch (Exception ex)
  197.             {
  198.                 OutLog(ex.ToString());
  199.             }
  200.             OutLog(string.Empty);
  201.         }
  202.         private void FrmTestHttpPost_Load(object sender, EventArgs e)
  203.         {
  204.             // Http方法
  205.             cboMode.SelectedIndex = 1;  // POST
  206.             cboContentType.SelectedIndex = 0; // json
  207.             // 回应的编码
  208.             cboResEncoding.Items.Clear();
  209.             _Encodings = Encoding.GetEncodings();
  210.             cboResEncoding.DataSource = _Encodings;
  211.             cboResEncoding.DisplayMember = "DisplayName";
  212.             _ResEncoding = Encoding.UTF8;
  213.             cboResEncoding.SelectedIndex = cboResEncoding.FindStringExact(_ResEncoding.EncodingName);
  214.         }
  215.         private void btnGo_Click(object sender, EventArgs e)
  216.         {
  217.             Encoding myEncoding = Encoding.UTF8;
  218.             string sMode = (string)cboMode.SelectedItem;
  219.             string sUrl = txtUrl.Text;
  220.             string sPostData = txtPostData.Text;
  221.             string sContentType = cboContentType.SelectedItem.ToString(); // "application/x-www-form-urlencoded";
  222.             TextReader read = new System.IO.StringReader(sPostData);
  223.             _OutputFileAllow = chkOutputFile.Checked;
  224.             _OutputFilePath = txtOutputFile.Text.Trim();
  225.             if (_OutputFileAllow && string.IsNullOrEmpty(_OutputFilePath)) {
  226.                 MessageBox.Show("The OutputFile textbox is empty!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
  227.                 return;
  228.             }
  229.             _HeaderLines = null;
  230.             if (chkHeader.Checked) {
  231.                 _HeaderLines = txtHeader.Lines;
  232.             }
  233.             // Log Length
  234.             //if (txtLog.Lines.Length > 3000) txtLog.Clear();
  235.             if (checkBox1.Checked)
  236.             {
  237.                 Task.Run(() =>
  238.                 {
  239.                     do
  240.                     {
  241.                         if (string.IsNullOrWhiteSpace(sUrl))
  242.                             break;
  243.                         sPostData = read.ReadLine();
  244.                         if (string.IsNullOrWhiteSpace(sPostData))
  245.                             break;
  246.                         // == main ==
  247.                         HttpReq(myEncoding, sMode, sUrl, sContentType, sPostData, checkBox2.Checked);
  248.                         Thread.Sleep((int)numericUpDown1.Value);
  249.                     } while (!string.IsNullOrWhiteSpace(sPostData));
  250.                 });
  251.             }
  252.             else
  253.             {
  254.                 // == main ==
  255.                 HttpReq(myEncoding, sMode, sUrl, sContentType, sPostData, checkBox2.Checked);
  256.             }
  257.         }
  258.         private void cboResEncoding_SelectedIndexChanged(object sender, EventArgs e)
  259.         {
  260.             EncodingInfo ei = cboResEncoding.SelectedItem as EncodingInfo;
  261.             if (null == ei) return;
  262.             _ResEncoding = ei.GetEncoding();
  263.         }
  264.         private void button1_Click(object sender, EventArgs e)
  265.         {
  266.             txtLog.Clear();
  267.         }
  268.     }
  269. }
复制代码
源码: https://github.com/zyl910/TestHttpPost
步调下载: https://github.com/zyl910/TestHttpPost/releases/tag/v1.2.1
参考文献

    出处:http://www.cnblogs.com/zyl910/    版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0.

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表