HTTPWebRequest:重复的帖子

时间:2013-09-24 10:54:17

标签: c# post httpwebrequest

我在下面有以下类来处理HTTP。我这样用它:

   HTTP http = new HTTP();
   string buffer = http.request("http://www.x.com", "username=user&pass=pass");

我正在使用httpAnalyzer查看数据。有时后期数据是正常的:

   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();
            }
        }
    }
  }

1 个答案:

答案 0 :(得分:0)

documentation提及:

  

您必须调用Stream.Close方法关闭流并释放连接以便重用。无法关闭流会导致应用程序用完连接。

HttpWebRequest重用连接下的连接,我可以对其进行映像,也可以重用流并简单地附加数据。如果发生这种情况,以下代码应解决问题:

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream))
{
    writer.Write(post);
}