使用WebRequest进行多次POST

时间:2013-02-07 15:28:50

标签: c# post webrequest

我可以发送第一个请求正常工作,但是我无法理解为什么第二次获取Stream os = smsRequest.GetRequestStream()时它停止了。

我知道您不能多次写入请求,这就是每次创建新实例的原因。

    public void SendSMS(Dictionary<double, IList<string>> texts)
    {
        if (CreateWebRequest())
        {
            foreach (double mpn in texts.Keys)
            {
                foreach (string sms in texts[mpn])
                {
                    string formParams = string.Format("sendTo=0{0}&selectText=Please+Select...&textMessage={1}&x=28&y=10", mpn, sms);
                    byte[] encodedParams = Encoding.UTF8.GetBytes(formParams);

                    HttpWebRequest smsRequest = CreateSMSRequest(encodedParams);

                    using (Stream os = smsRequest.GetRequestStream())
                    {
                        os.Write(encodedParams, 0, encodedParams.Length);
                        os.Close();
                    }
                }
            }
        }
    }


    private HttpWebRequest CreateSMSRequest(byte[] encodedParams)
    {
        HttpWebRequest smsRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
        smsRequest.Method = WebRequestMethods.Http.Post;
        smsRequest.ContentType = "application/x-www-form-urlencoded";
        smsRequest.ContentLength = encodedParams.Length;
        smsRequest.AllowAutoRedirect = false;
        smsRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
        smsRequest.Headers.Add(HttpRequestHeader.Cookie, _cookieData);

        return smsRequest;
    }

1 个答案:

答案 0 :(得分:1)

我认为您的回答与此相同: HttpWebRequest getRequestStream hangs on multiple runs

在你的使用声明之后:

var response = smsRequest.GetResponse() as HttpWebResponse;