我在下面有以下类来处理 HTTP。我这样使用它:
HTTP http = new HTTP();
string buffer = http.request("http://www.x.com", "username=user&pass=pass");
我正在使用 httpAnalyzer 查看数据。有时候post数据是正常的:
username=user&pass=pass
有时它会像这样发布:
username=user&pass=passusername=user&pass=pass
即使“内容长度”在两种情况下都保持不变。关于它为什么会这样的任何提示?谢谢!
public partial class HTTP {
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 2048;
const int DefaultTimeout = 500000;
public CookieContainer cookies = new CookieContainer();
public string GET(string url, string post)
{
string buffer = "";
Console.WriteLine(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookies; request.KeepAlive = true;
System.Net.ServicePointManager.Expect100Continue = false;
request.Accept = "*/*";
request.Headers.Add("Accept-Encoding", "deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
request.Referer = "https://www.host.com";
request.KeepAlive = true;
System.Net.ServicePointManager.Expect100Continue = false;
RequestState myRequestState = new RequestState();
AutoResetEvent ev = new AutoResetEvent(false);
request.KeepAlive = true;
request.AllowAutoRedirect = true;
StringBuilder sb = new StringBuilder();
if (post.Length > 0)
{
request.Method = "POST";
request.ContentLength = post.Length;
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(post);
writer.Close();
}
ThreadPool.RegisterWaitForSingleObject(ev, new WaitOrTimerCallback(TimeoutCallback), request, DefaultTimeout, true);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
buffer = "";
buffer = reader.ReadToEnd();
for (int i = 0; i < response.Headers.Count; i++)
{
string name = response.Headers.GetKey(i);
string value = response.Headers.Get(i);
if (name == "Set-Cookie")
{
Match match = Regex.Match(value, "(.+?)=(.+?)");
string[] tmp = value.Split('=');
if (match.Captures.Count > 0)
{
Uri u = new Uri("https://www.host.com");
cookies.SetCookies(u, tmp[0] + "=" + tmp[1]);
}
}
}
request.CookieContainer = cookies;
response.Close();
reader.Close();
return buffer;
}
public class RequestState
{
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] BufferRead;
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
streamResponse = null;
}
}
private static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
HttpWebRequest request = state as HttpWebRequest;
if (request != null)
{
request.Abort();
}
}
}
}