[英]Xml Request and response from a URL
我正在嘗試從 URL 獲得響應,該響應采用 Xml 輸入並返回 Xml Z78E66221F63983D1CE31
And there is this case when this Url returns Bad Request 400, in this case in code I'll get an exception and I can't view the Xml, but if I tried the same input in postman I'll get the Xml output.
In case of the exception I can catch this exception by using WebException , but here in the end when I read the response using reader.ReadToEnd() I'll get a JSON not the Xml output that I got from postman
Postman output 示例:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<RESPONSE MODE="DIRECT" TYPE="PINPRINTING">
<RESULTMESSAGE>User not allowed to process</RESULTMESSAGE>
</RESPONSE>
這是我的代碼:
public void GetResponse()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURL);
request.Accept = "application/xml";
byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(requestXmlDoc.InnerXml);
request.Method = "POST";
request.ContentType = "text/xml;charset=utf-8";
request.ContentLength = requestInFormOfBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestInFormOfBytes, 0, requestInFormOfBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
string receivedResponse = respStream.ReadToEnd();
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data, ASCIIEncoding.ASCII))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
}
返回的 JSON 是這樣的:
{
"status": 400,
"statusDesc": "Invalid input"
}
嘿,我找到了答案,它是內容類型。 更改:request.ContentType = "text/xml;charset=utf-8"; 到這個 request.ContentType = "application/xml"; 現在我得到了我需要的 Xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.