Xml Request and response from a URL - c#

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

Related

c# how to get unknown list of attributes

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("что то не так");
}

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream getting this error

i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here

Parsing POST request data with FiddlerCore

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?
Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

Remote Server returns error 401 Unauthorized Webexception (POST)

I'm trying to solve an issue that I Mostly (70%) have (30% is succesfull).
I trying to do a webrequest (POST) with the following code:
private string HttpWebRequest(string busStopCode)
{
//XML input
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>"+busStopCode+"</MonitoringRef></StopMonitoringRequest></ServiceRequest></Siri>";
string responseFromServer = null;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://<username>:<username>#nextbus.mxdata.co.uk/nextbuses/1.0/1");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultNetworkCredentials;
// Create POST data and convert it to a byte array.
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// 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 = null;
while (response == null)
{
try
{
response = request.GetResponse();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription + " Completed");
// 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.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
When I call this function I get mostly a messagebox of my exception with:
"System.Net.WebException: The remote Server returned an error(401) not authorized with System.Net.Http.Webrequest.GetResponse() with WindowsFormApplication1.Form1.HttpWebRequest(string BusstopCode) in <my pathfile>...."
What I'm doing wrong?
I already tried several solutions from previous threads but without success...
Thanks!

HttpWebRequest doesn't work every time

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");

Categories

Resources