gpt4 book ai didi

c# - Stream 和 XmlTextwriter.... 未正确收到请求

转载 作者:行者123 更新时间:2023-11-30 21:22:38 25 4
gpt4 key购买 nike

我卡在了这个 httpWebRequest 问题上。我需要将 XML 发送到网站。但我的要求不断得到否定的回应。我看到了一些设置了 ContentLength 的代码示例……这可能是问题所在,但我不知道……

用 writePaymentRequest(...) 编写的 XML 完全符合网站的需要,因为他们得到了我的 xml 标记并且他们成功了,不过是用另一种编程语言。结果只包含他们的错误,而不是我应该收到的信息。

我无法设置内容长度,因为我在创建带有请求流的编写器时不知道长度。

HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("https://some.website.com");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";

using (writer = new XmlTextWriter(httpWebRequest.GetRequestStream(), System.Text.Encoding.UTF8))
{
writePaymentRequest(writer, registrant, amount, signature, ipaddress);
}

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
String stringResult = streamReader.ReadToEnd();
streamReader.Close();

最佳答案

如果您首先将 XmlTextWriter 写入类似 MemoryStream 的内容,您就会知道长度。从那里,您可以获取字节,将 httpWebRequest.ContentLength 设置为字节数组的长度,然后将字节数组写入您的请求

编辑

你的代码的中间部分看起来像这样(我认为):

    MemoryStream ms = new MemoryStream();
using (writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8))
{
writePaymentRequest(writer, registrant, amount, signature, ipaddress);
}
byte[] bytes = ms.ToArray();
ms.Close();
httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
httpWebRequest.ContentLength = bytes.Length;

编辑 #2

代替 XmlTextWriter(ms, System.Text.Encoding.UTF8),试试 XmlTextWriter(ms, new UTF8Encoding(false)) 看看是否修复了编码问题

关于c# - Stream 和 XmlTextwriter.... 未正确收到请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2177231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com