HttpWebRequest Post方法发送部分数据

本文关键字:数据 送部 Post 方法 HttpWebRequest | 更新日期: 2023-09-27 18:24:18

我有以下代码来向服务器发送POST请求。

HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
myWebRequest.Method = WebRequestMethods.Http.Post;
myWebRequest.ContentLength = data.Length;
myWebRequest.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(myWebRequest.GetRequestStream());
writer.Write(data);
writer.Close();

要发布的数据是一个包含近2000个字符的XML请求。我阅读了如下所示的回复。

this.Response.ContentType = "text/xml";
StreamReader reader = new StreamReader(this.Request.InputStream);
string responseData = reader.ReadToEnd();

我们在上面获得的响应数据只有实际发送数据的一部分。

请帮我获取完整的数据。

HttpWebRequest Post方法发送部分数据

这对我很有效,我想你错过了编码。。。使用这个,我将巨大的xml发送到服务器

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(connectionString);
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        WebResponse response = request.GetResponse();
        //Console.WriteLine("Service Status Code:"+((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();

我做这件事的方式与您的方式略有不同:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = DataToPost.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(DataToPost);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());

这种方式已经使用多年了。