Error uploading items with Walmart marketplace API feed - c#

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;
}

Related

System.Xml.Linq.XContainer.Element(...) returned null

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

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;
}

Response returning html code instead of XML

I am sending XML data using HTTP POST to a specified URL.Expected response is to be in XML format. But I am receiving HTML code instead of XML.I am sending my sample post code.
string postData = null;
postData = "NETCONNECT_TRANSACTION=" + System.Web.HttpUtility.UrlEncode(xdoc.ToString());
HttpWebRequest experianRequest = (HttpWebRequest)WebRequest.Create("some url");
experianRequest.Method = "POST";
experianRequest.ContentType = "application/x-www-form-urlencoded";
string UserIDFormated = "username:password";
experianRequest.Headers.Add("Authorization: BASIC" + ConvertToBase64String(UserIDFormated));
experianRequest.Timeout = 100000;
experianRequest.KeepAlive = false;
experianRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteData;
byteData = encoding.GetBytes(postData);
experianRequest.AllowAutoRedirect = true;
experianRequest.ContentLength = byteData.Length;
Stream newStream = experianRequest.GetRequestStream();
newStream.Write(byteData, 0, byteData.Length);
newStream.Close();
HttpWebResponse experianResponse = (HttpWebResponse)experianRequest.GetResponse();
StreamReader reader = new StreamReader(experianResponse.GetResponseStream(), Encoding.UTF8);
//XmlTextReader objxml = new XmlTextReader(newStream2);
//XmlDocument xdocresponse = new XmlDocument();
//xdocresponse.Load(experianResponse.GetResponseStream());
//string root = xdocresponse.DocumentElement.OuterXml;
//XDocument xdocresponse = XDocument.Load(objxml);
//objxml.Close();
//experianResponse.Close();
//StreamReader reader = new StreamReader(newStream2);
string responseFromServer = reader.ReadToEnd();
reader.Close();
//newStream.Close();
experianResponse.Close();

Restful wcf Service error 'Unable to deserialize XML body with root name

I have written a RESFful service for a phone app.
I am not sure what am I doing wrong? I tried to test it with multiple content type settings but no luck.
The data from a phone app is coming encoded in following format.
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
This is the definition in the interface:
[OperationContract]
[WebInvoke]
String GetUserInfo(String authenticateRequest);
I get error: with following test code.
'Unable to deserialize XML body with root name 'Binary' and root namespace '' (for operation 'GetMobileCheckCapture' and contract ('IMobileCC', 'http://tempuri.org/')) using DataContractSerializer
This is how I am trying to test the service:
String encryptedSAML =
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(bDataToPass, 0, bDataToPass.Length);
}
try
{
using (WebResponse webresponse = req.GetResponse())
{
StreamReader reader = null;
string responses = "";
string StatusDescription = ((HttpWebResponse)webresponse).StatusDescription;
if (((HttpWebResponse)webresponse).StatusCode != HttpStatusCode.OK)
{
// Console.Write();
}
reader = new StreamReader(webresponse.GetResponseStream());
responses = reader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(responses.Replace("&", "&"));
response = xmldoc;
}
}
catch (WebException e)
{
using (WebResponse response2 = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response2;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response2.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
Have you tried to use UTF-8 encoding instead of ASCII?
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
UTF8Encoding encoding = new UTF8Encoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;

Categories

Resources