문제

Im stuck on this httpWebRequest problem. I need to send XML to a website. But I keep getting negative responses on my request. I saw some code examples where the ContentLength was set... And that might be the issue but I don't know....

The XML written in writePaymentRequest(...) is exactly as the website needs it to be, because they got my xml markup and they succeeded, in another programming language though. The result only contains their error instead of the information I'm supposed to be receiving.

I can't set the contentlength because I don't know the length when I create the writer with the requeststream in it.

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();
도움이 되었습니까?

해결책

You would know the length if you wrote the XmlTextWriter to something like a MemoryStream first. From there, you could get the bytes, set the httpWebRequest.ContentLength to the length of the byte array, and then write the byte array to your request

edit

The middle of your code would look something like this (I think):

    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;

edit #2

Instead of XmlTextWriter(ms, System.Text.Encoding.UTF8), try XmlTextWriter(ms, new UTF8Encoding(false)) to see if that fixes the encoding issue

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top