有时候需要看网页的提交效果,但需要改变一些自己的参数,于是想到了做个这样的工具
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace HTTPGetPost
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGo_Click(object sender, EventArgs e)
{
if (rdbGet.Checked)
{
txtRe.Text = GetData(txtUrl.Text, txtHead.Text);
}
else
{
txtRe.Text = GetData(txtUrl.Text, txtHead.Text,txtPost.Text );
}
}
private string GetData(string url, string head,string post)
{
WebClient wc = AddHead(txtHead.Text);
byte[] re = wc.UploadValues(url, "POST", PostData(post));
return EncodeHtml(re);
}
private string GetData(string url, string head)
{
WebClient wc = AddHead(txtHead.Text);
byte[] re = wc.DownloadData(url);
return EncodeHtml(re);
}
private WebClient AddHead(string head)
{
WebClient wc = new WebClient();
string[] p = head.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < p.Length; i++)
{
int k = p[i].IndexOf("\t");
wc.Headers.Add (p[i].Substring(0, k), p[i].Substring(k + 1, p[i].Length - k - 1));
}
wc.Credentials = CredentialCache.DefaultCredentials;
return wc;
}
private NameValueCollection PostData(string poststr)
{
NameValueCollection PostVars = new NameValueCollection();
string[] p=poststr.Split (new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < p.Length; i++)
{
int k=p[i].IndexOf ("\t");
PostVars.Add (p[i].Substring (0,k),p[i].Substring (k+1,p[i].Length -k -1));
}
return PostVars;
}
private string EncodeHtml(byte[] myDataBuffer)
{
string strWebData = Encoding.UTF8.GetString(myDataBuffer);
Match charSetMatch = Regex.Match(strWebData, "(?<=<meta.*charset=).*?(?=\")", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (charSetMatch.Value == "")
{
charSetMatch = Regex.Match(strWebData, "(?<=<meta.*charset=).*?(?=;)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
}
if (charSetMatch.Value == "")
return strWebData;
else
{
return System.Text.Encoding.GetEncoding(charSetMatch.Value).GetString(myDataBuffer);
}
}
}
}