【问题标题】:Sending http post request returns partial results发送 http post 请求返回部分结果
【发布时间】:2012-08-31 17:52:58
【问题描述】:

我正在编写一个简单的服务器端应用程序,它将请求发送到远程休息服务。 当我使用此代码示例通过我的代码发送它时:

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";

// Create POST data and convert it to a byte array.
var paramsBuilder = new StringBuilder();
foreach (var param in parameters)
{
    paramsBuilder.AppendFormat("&{0}={1}", param.Key, param.Value);
}
paramsBuilder.Length--;

byte[] byteArray = Encoding.UTF8.GetBytes(paramsBuilder.ToString());
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// 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();
// Get the response.
WebResponse response = request.GetResponse();
// 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();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;

我得到了部分结果。内容没有被修剪,只是部分内容。 当我通过hurl.it 之类的服务发送相同的请求时,我会得到完整的响应。

可能是什么原因造成的?

【问题讨论】:

  • 不完全确定这里出了什么问题,但您能更具体地了解部分结果吗?你得到了多少,缺少了什么?

标签: c# http-post


【解决方案1】:

这可能是因为服务器在响应中使用的编码

检查这个问题partial page source from httpwebresponse

链接到http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx

这解释了 “StreamReader 使用的默认编码 (UTF8) 可能与您正在读入 StreamReader 的字节的编码不匹配。”

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2015-12-19
    相关资源
    最近更新 更多