请求.ContentLength = byteArray.Length;它将再次以相同的方法引发异常

本文关键字:方法 异常 byteArray ContentLength Length 请求 | 更新日期: 2023-09-27 18:35:46

public void sendSingleSMS(String username, String password, String senderid, String mobileNo, String message)
{
        request.ContentLength = 0;
        String smsservicetype = "singlemsg"; //For single message.
        String query = "username=" + HttpUtility.UrlEncode(username) + "&password=" + HttpUtility.UrlEncode(password) + "&smsservicetype=" + HttpUtility.UrlEncode(smsservicetype) + "&content=" + HttpUtility.UrlEncode(message) + "&mobileno=" + HttpUtility.UrlEncode(mobileNo) + "&senderid=" + HttpUtility.UrlEncode(senderid);
        byte[] byteArray = Encoding.UTF8.GetBytes(query);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;            
        dataStream = request.GetRequestStream();            
        dataStream.Write(byteArray, 0, byteArray.Length);           
        dataStream.Close();           
        WebResponse response = request.GetResponse();            
        String Status = ((HttpWebResponse)response).StatusDescription;
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        //byteArray.clear(0);
        //byteArray.length = 0;
        dataStream.Close();
        response.Close();
        //request.ContentType = null;
        request.Abort();
}

请帮助我们摆脱此错误...

我想重用一个WebRequest对象,以便保存cookie和会话,以便以后向服务器请求。下面是我的代码。如果我第二次使用 Post 功能两次

请求。ContentLength = byteArray.Length;它将引发异常

写入开始后无法设置此属性!但如您所见

dataStream.Close();应该关闭写作过程!有人知道发生了什么吗?

请求.ContentLength = byteArray.Length;它将再次以相同的方法引发异常

为了保留cookie(以及会话),您需要使用HttpWebRequest及其CookieContainer

首先创建它:

CookieContainer cookieJar = new CookieContainer();

然后,将其分配给您的请求:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieJar;

然后你做任何你想做的事情(发送请求,获取响应,处理响应......然后你可以创建另一个请求并"重用"cookieJar:

HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(url2);
request2.CookieContainer = cookieJar;

第二个请求将使用包含来自第一个请求-响应的 cookie 的相同 cookieJar。