How to display response in Xml format? - c#

I want to display in console the response from request in pretty Xml format, I write code but console displays nothing.
What I want from project is: there some Xml requests (they should work step by step), if (for example) result from first (checkPaymentRequisites) request is equal from 0 and status == 3, then send (go to) second (addOfflinePayment) request. Below codes:
Main method:
public static string postXMLData(string destinationUrl, string xml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
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)
{
Stream responseStream = response.GetResponseStream();
var xmlResponce = XmlToResponce(responseStream);
if (xmlResponce.Providers.checkPaymentRequisites.Payment.result == 0 && xmlResponce.Providers.checkPaymentRequisites.Payment.status == 3)
{
xml=Requests.addOfflinePayment();
}
else
{
Console.WriteLine("Something wrong");
}
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return string.Empty;
}
Responses:
//Responses
//checkPaymentRequisites
private static Responses.Response XmlToResponce (Stream stream)
{
var xmlSerializer = new XmlSerializer(typeof(Responses.Response));
var xmlResponce = xmlSerializer.Deserialize(stream) as Responses.Response;
return xmlResponce;
}
//addOfflinePayment
private static Responses.ResponseOff XmlToResOff(Stream stream)
{
var xmlSerializer = new XmlSerializer(typeof(Responses.ResponseOff));
var xmlResponce = xmlSerializer.Deserialize(stream) as Responses.ResponseOff;
return xmlResponce;
}
Diplaying to console:
static void Main(string[] args)
{
string str = Requests.checkPaymentRequisites();
var xml = postXMLData(url, str);
Console.WriteLine(xml);
Console.ReadKey();
}
I tried some copy-past from other place of code to other place )))) (stupid things), no result

Related

I am trying to write a console app in c# that consume a web service running on tomcat, to perform a "PUT" method with an xml file

public static String TransferMessage(String uri, String resource,
String xml_data, Method httpmethod,
ReturnType returnType)
{
try
{
WebRequest request = WebRequest.Create(uri + resource);
request.Method = httpmethod.ToString();
request.ContentType = #"application/xml;";
//request.Headers.Add("Token", token);
request.Timeout = Convert.ToInt32((new TimeSpan(1, 0, 0)).TotalMilliseconds);
request.ContentLength = Encoding.UTF8.GetByteCount(xml_data);
if (httpmethod != Method.GET)
using (Stream stream = request.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(xml_data), 0,
Encoding.UTF8.GetByteCount(xml_data));
stream.Flush();
stream.Close();
}
return getResponseContent(request.GetResponse());
}
catch(Exception e)
{
Console.WriteLine(e);
}
return null;
}
Main method:
var res_xml = MethodHelper.TransferMessage(endpoint, "/" + resource,xml,
MethodHelper.Method.PUT,
MethodHelper.ReturnType.XML);
I am getting this error
ERROR javax.xml.bind.UnmarshalException\n - with
linked exception:\n[org.xml.sax.SAXParseException; line Number: 1;
columnNumber: 1; Content is not allowed in prolog.]
try{
string contend = "";
using (var streamReader = new StreamReader(new FileInfo(#"C:\Users\absmbez\Desktop\temp\upload.xml").OpenRead()))
{
contend = streamReader.ReadToEnd();
}
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "PUT";
webrequest.ContentType = "application/xml";
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
byte[] requestData = enc.GetBytes(contend);
webrequest.ContentLength = requestData.Length;
using (var stream = webrequest.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
webresponse.Close();
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
}

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

HttpWebRequest GET returns 'No Content' after successful POST

I'm working on an app that makes a POST to a REST API that returns a URI in its response. I then am to make a GET request to that URI and it is supposed to return HTML content in the response body. However, the GET request returns 'No Content' in its HTTP Status Code.
What's strange is, I have a small console app I built for testing purposes that if I plug the URI into it (allows me to test the GET without making the POST), the status good is 200 - OK and I receive the HTML content in the body. So it seems it is related to something I'm doing in my POST request. Here is my code (sensitive info has been redacted):
private PersonReportResults POSTReportRequest(PersonReportRequest reportRequest)
{
var personReportResults = new PersonReportResults();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxxxxxx.com/api/v1/personReport/reportResults");
var xDoc = new XmlDocument();
var serializedXml = Serialize(reportRequest);
xDoc.LoadXml(serializedXml);
var bytes = Encoding.ASCII.GetBytes(xDoc.OuterXml);
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["XXXXXUserId"], ConfigurationManager.AppSettings["XXXXXPassword"]);
request.ClientCertificates.Add(GetClientCertificate());
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseStream = response.GetResponseStream();
using (MemoryStream ms = new MemoryStream())
{
var count = 0;
do
{
byte[] buf = new byte[1024];
count = responseStream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (responseStream.CanRead && count > 0);
ms.Position = 0;
// now attempt to desrialize from the memory stream
var serializer = new XmlSerializer(typeof(PersonReportResults));
personReportResults = ((PersonReportResults)serializer.Deserialize(ms));
}
response.Close();
}
request.Abort();
}
return personReportResults;
}
/// <summary>
/// Makes a HTTP GET request for the report HTML
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns>string</returns>
private static string GETResults(string uri)
{
var responseHTML = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + "?reportType=html");
//request.ContentType = "application/xml; encoding='utf-8'";
request.Method = "GET";
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["XXXXXUserId"], ConfigurationManager.AppSettings["XXXXXPassword"]);
request.ClientCertificates.Add(GetClientCertificate());
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (MemoryStream ms = new MemoryStream())
{
var count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
ms.Position = 0;
var sr = new StreamReader(ms);
responseHTML = sr.ReadToEnd();
}
//var reader = new StreamReader(stream, Encoding.UTF8);
//responseHTML = reader.ReadToEnd();
}
}
}
catch (Exception e)
{
}
request.Abort();
}
else if (response.StatusCode == HttpStatusCode.Accepted)
{
response.Close();
var tryCount = 1;
while (tryCount < 5)
{
using (var retryResponse = (HttpWebResponse)request.GetResponse())
{
if (retryResponse.StatusCode == HttpStatusCode.OK)
{
using (var stream = retryResponse.GetResponseStream())
{
if (stream != null)
{
var reader = new StreamReader(stream, Encoding.UTF8);
responseHTML = reader.ReadToEnd();
}
}
}
}
tryCount++;
Thread.Sleep(10000);
}
}
}
return responseHTML;
}

ReCaptcha Post Using C# in MVC Application

I'm trying to do a direct post to Google using this code. I keep getting an error, "invalid private key". I have double checked it and even had someone else double check it. The reason i'm going it this way is because I'm using javascript and ajax to pass the variables to this function.
[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
if (captchaChallenge != null && captchaResponse != null)
{
string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"].ToString();
string strParameters = "?privatekey=" + strPrivateKey +
"&remoteip=" + HttpContext.Request.UserHostAddress.ToString() +
"&challenge=" + captchaChallenge +
"&response=" + captchaResponse;
WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
request.Method = "POST";
string postData = strParameters;
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();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
if (responseFromServer.ToString() != "true")
{
errorCodeList.Add(8);
return responseFromServer + strPrivateKey;
}
else
{
return responseFromServer;
}
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
else
{
errorCodeList.Add(8);
return null;
}
}
The "return" in the IF/ELSE means thet that the "Clean up the streams" code is unreachable and as the return withing the IF would end the execution, this could be simplified a little:
[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
if (captchaChallenge != null && captchaResponse != null)
{
// original code, remains unchanged
/*
...snipped for clarity
*/
// Clean up the streams (relocated to make it reachable code)
reader.Close();
dataStream.Close();
response.Close();
if (responseFromServer.ToString() != "true")
{
errorCodeList.Add(8);
return responseFromServer + strPrivateKey; // "IF" ends execution here
}
return responseFromServer; // "ELSE" ends execution here
}
errorCodeList.Add(8);
return null;
}
I guess you need to delete ? on post data.
I've changed the code for me, and this works
private bool ValidarCaptcha(UsuarioMV usuarioMV)
{
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
try
{
string captchaChallenge = usuarioMV.sCaptchaChallenge;
string captchaResponse = usuarioMV.sCaptchaResponse;
if (captchaChallenge != null
&& captchaResponse != null)
{
throw new Exception("Parametros captcha nulos.");
}
WebRequest request = WebRequest.Create("https://www.google.com/recaptcha/api/verify");
request.Method = "POST";
//Solicitud
string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["RecaptchaPrivateKey"].ToString();
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("privatekey", strPrivateKey);
outgoingQueryString.Add("remoteip", "localhost");
outgoingQueryString.Add("challenge", captchaChallenge);
outgoingQueryString.Add("response", captchaResponse);
string postData = outgoingQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
//Respuesta
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
if (reader.ReadLine() != "true")
{
string sLinea = reader.ReadLine();
//if the is another problem
if (sLinea != "incorrect-captcha-sol")
{
throw new Exception(sLinea);
}
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw;
}
finally
{
//Clean up the streams.
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
if (response != null)
response.Close();
}
}
You can try like this basically. I got affirmative result !!!
public async Task<bool> ReCaptcha(Recaptcha recaptcha)
{
string secretKey = "YOUR_PRIVATE_KEY";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, recaptcha.Response), null);
if (response.IsSuccessStatusCode)
{
var resultString = await response.Content.ReadAsStringAsync();
RecaptchaResponse resp = JsonConvert.DeserializeObject<RecaptchaResponse>(resultString);
if (resp.success)
{
return true;
}
}
return false;
}

How to get value back from a web services in C#?

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

Categories

Resources