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();
Related
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("что то не так");
}
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
I am trying to upload items with Walmart marketplace APIs(Bulk Create Item)
but always get a response as 500 Internal server error. Any Ideas?
the other Api functions are okay but not this func..
Actually Others are using Method is "application/xml" but this is using "multipart/form-data;"
Note that the XML strings/example in the code below are taken from https://developer.walmartapis.com/#the-item-object and then I changed IDs property.
public bool RequestUpdateItem()
{
string strBaseUrl = string.Format("https://marketplace.walmartapis.com/v2/feeds?feedType=item");
string strRequestMethod = "POST";
WalmartSignature Signature = new WalmartSignature(consumerId, privateEncodedStr, strBaseUrl, strRequestMethod);
string strSignature = string.Empty;
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
WalmartOrderModel orderModel = new WalmartOrderModel();
StringBuilder strBuilder = new StringBuilder();
bool bReturnValue = false;
try
{
strSignature = Signature.GetSignature(null); // null -> generate timestamp
httpWebRequest = (HttpWebRequest)WebRequest.Create(strBaseUrl);
httpWebRequest.Method = strRequestMethod;
httpWebRequest.Accept = "application/xml";
httpWebRequest.ContentType = "multipart/form-data;";
httpWebRequest.Headers.Add("WM_SVC.NAME", "Walmart Marketplace");
httpWebRequest.Headers.Add("WM_SEC.AUTH_SIGNATURE", strSignature);
httpWebRequest.Headers.Add("WM_CONSUMER.ID", Signature.ConsumerId);
httpWebRequest.Headers.Add("WM_SEC.TIMESTAMP", Signature.TimeStamp);
httpWebRequest.Headers.Add("WM_QOS.CORRELATION_ID", Guid.NewGuid().ToString());
string strRequestBody =
#"<?xml version=""1.0"" encoding=""UTF-8""?>
<MPItemFeed xmlns=""http://walmart.com/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://walmart.com/MPItem.xsd"">
<MPItemFeedHeader>
<version>2.1</version>
<requestId>333pecEl55nics</requestId>
<requestBatchId>333ecElect55cs38</requestBatchId>
</MPItemFeedHeader>
<MPItem>
<sku>BDK72wsd44f</sku>
<Product>
<productName>QVS</productName>
<longDescription>QVS</longDescription>
<shelfDescription>QVS</shelfDescription>
<shortDescription>QVS</shortDescription>
<mainImage>
<mainImageUrl>http://images.antonline.com/img-main/500/037229400328.jpg</mainImageUrl>
</mainImage>
<productIdentifiers>
<productIdentifier>
<productIdType>UPC</productIdType>
<productId>220740171234</productId>
</productIdentifier>
</productIdentifiers>
<productTaxCode>2038710</productTaxCode>
<additionalProductAttributes>
<additionalProductAttribute>
<productAttributeName>product_id_override</productAttributeName>
<productAttributeValue>true</productAttributeValue>
</additionalProductAttribute>
</additionalProductAttributes>
<Electronics>
<brand>QVS</brand>
<ElectronicsCables>
</ElectronicsCables>
</Electronics>
</Product>
<price>
<currency>USD</currency>
<amount>99.29</amount>
</price>
<shippingWeight>
<value>0.12</value>
<unit>LB</unit>
</shippingWeight>
</MPItem>
</MPItemFeed>";
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(strRequestBody);
writer.Flush();
stream.Position = 0;
httpWebRequest.ContentLength = stream.Length;
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
stream.CopyTo(requestStream);
//requestStream.Write(stream, 0, stream.Length);
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode == HttpStatusCode.OK)
{
Stream streamResponse = httpWebResponse.GetResponseStream();
var responseResult = XDocument.Load(streamResponse);
}
}
}
catch (Exception ex)
{
Console.WriteLine("RequestUpdateItem(): " + ex);
}
return bReturnValue;
}
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;
}
I want to post a request on server using POST and webrequest?
I need to pass parameters as well while posting?
how can i pass the parameters while posting?
How can i do that???
Sample code...
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
you can try with this code
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();