When I send request I will get like this response:
<?xml version="1.0" encoding="UTF-8"?>
<response result="0">
<check result="0">
<extras PRV_TXN_ID="538659" disp1="text1" disp2="text2" disp3="text3"/>
</check>
</response>
I want to show in console list of disp attributes. Quantity of disp attributes are unknown, depends on requests. Sometimes there will be disp1.....disp8 . Here in this response there 3 disp' attributes and before getting response I didn't know how many are they. How to do that?
Here my Parsing:
public static XmlDocument postXMLData(string xml)
{
var request = (HttpWebRequest)WebRequest.Create(Requests.url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
var result = new XmlDocument();
result.LoadXml(responseText);
return result;
}
}
throw new Exception("что то не так");
}
Related
I have postXmlData method to post request and get response in Xml. After receiveng responce I am trying to show attributes name startswith ("f"), but getting error System.Xml.Linq.XContainer.Element(...) returned null. What am I doing wrong?
postXmlData
public static XmlDocument postXMLData(string xml)
{
var request = (HttpWebRequest)WebRequest.Create(Requests.url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
var result = new XmlDocument();
result.LoadXml(responseText);
return result;
}
}
throw new Exception();
}
Response from Request:
<response result="0">
<prov>
<getStatus result="0">
<pay date="2023-02-08T19:44:33+03:00" fatal="false" id="8022140013003" result="0" status="2" uid="26775263057008" value-date="2023-02-08T19:44:40+03:00">
</pay>
</getStatus>
</prov>
</response>
To show attributes I am using XElement:
XmlDocument doc = postXMLData(Requests.getStatus("08022140013003"));
XElement e = XElement.Load(new XmlNodeReader(doc));
Console.WriteLine(e); //here ok
IEnumerable<XAttribute> attrs1 = e.Element("response").Element("prov").Element("getStatus").Element("pay")?.Attributes().Where(a => a.Name.LocalName.StartsWith("f"));
Console.WriteLine(attrs1);
Console.ReadKey();
Try with:
var attrs1 = e.Element("prov").Element("getStatus").Element("pay").Attributes().Where(a => a.Name.LocalName.StartsWith("f"));
You can validate this by doing:
var elements = e.Elements()
There is only 1 element and it is not response but prov.
Edit:
XmlDocument doc = postXMLData(Requests.getStatus("08022140013003"));
XElement e = XElement.Load(new XmlNodeReader(doc));
//This line:
var elementsArray = e.Elements().ToArray();
Console.WriteLine(e); //here ok
IEnumerable<XAttribute> attrs1 = e.Element("response").Element("prov").Element("getStatus").Element("pay")?.Attributes().Where(a => a.Name.LocalName.StartsWith("f"));
Console.WriteLine(attrs1);
Console.ReadKey();
I'm trying to get a response from a URL which takes an Xml input and returns an Xml output.
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 example:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<RESPONSE MODE="DIRECT" TYPE="PINPRINTING">
<RESULTMESSAGE>User not allowed to process</RESULTMESSAGE>
</RESPONSE>
and this is my code:
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);
}
}
}
}
the returned JSON is something like this:
{
"status": 400,
"statusDesc": "Invalid input"
}
Heh I found the answer it was the content type.
changed:
request.ContentType = "text/xml;charset=utf-8";
to this
request.ContentType = "application/xml";
and now I get the Xml that I need
i received an Error when i am posting a XML file via HttpWebRequest. I would like to show the response as an label.
My Code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https:xxxxxxxxxxxx");
byte[] bytes;
var file = Environment.SpecialFolder.MyDocuments + "\\myRequest.xml";
bytes = System.Text.Encoding.ASCII.GetBytes(file);
request.Headers.ToString();
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
label13.Text = responseStr;
}
My Response in label13.Text = The supplied data could not be imported in the stated format -[XML2Array] Error parsing the XML String
I'm doing a WebRequest to a Uri but the problem is that I don't get a response every time. Sometimes I need to redo it. I would like my program to check if it got no response and if so the program will automatically recall the method for the WebRequest until I get a response.
In pseudocode
while(response == null)
{
try it again
}
This is my function. The capital comment is the explanation of my issue
private string HttpWebRequest()
{
string xml = #"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Siri version='1.0' xmlns='http://www.siri.org.uk/'>
<ServiceRequest>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<RequestorRef><USERNAME></RequestorRef>
<StopMonitoringRequest version='1.0'>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<MessageIdentifier>12345</MessageIdentifier>
<MonitoringRef>020035811</MonitoringRef>
</StopMonitoringRequest>
</ServiceRequest>
</Siri>";
string responseFromServer = null;
WebRequest request = WebRequest
.Create("http://<USERNAME>:<PASSWORD>#nextbus.mxdata.co.uk/nextbuses/1.0/1");
request.Method = "POST";
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
////////IF I GET NO RESPONSE EVERYTHING AFTER THE NEXT LINE WILL BE IGNORED
WebResponse response = request.GetResponse();
///////////THIS MESSAGEBOX WILL BE IGNORED
MessageBox.Show(((HttpWebResponse)response).StatusDescription+" Completed");
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
How can I resolve this?
If you want to just retry if the returned result ends up being null.. why not just do something like:
private void RunWebrequest()
{
if (HttpWebRequest() == null)
{
RunWebrequest();
}
else
{
//continue
}
}
I had the same 401 issue with this server, instead of placing your username & password in the url as per the traveline documentation use "Credentials" instead:-
string travelineUrl = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
var travelineRequest = (HttpWebRequest)WebRequest.Create(travelineUrl);
travelineRequest.Credentials = new NetworkCredential("yourusername", "yourpassword");
I am sending a URL and XML to a webservices, so that it will return me JSON about the result. I am here posting the request to the webservices how do I get the value from the webservices back. The value returned by the webservices is JSON. What should be the return type here and what should be returned to get the HTTP response status and body
public string HttpPostcredentials(string XML, string url)
{
try
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
req.ContentType = "application/xml";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
}
catch (Exception e)
{
}
return null;
}
Is this what you are looking for:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = "POST";
}
byte[] requestBodyBytes = Encoding.ASCII.GetBytes(XML);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
You need to get the Response from the HttpWebRequest
WebResponse result = req.GetResponse();