0

Trying to upload an xml file, this particular server is returning an error (exception above). I have tried another url, on another server (https://posttestserver.com/post.php), and the code worked. My co-worker was able to upload the same xml file via a Perl Script.

My question is: Is there another way to upload the contents of the file? Tried UploadData, UploadString, got the same error.

// Create the xml document file
Byte[] buffer = new Byte[ms.Length];
buffer = ms.ToArray();
xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);
string filePath = @"c:\my.xml");
File.WriteAllText(filePath, xmlOutput);

try
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

    using (WebClient client = new WebClient())
    {
        byte[] rawResponse = client.UploadFile(url, filePath); 
        string response = System.Text.Encoding.ASCII.GetString(rawResponse);    
    }
}
catch (WebException ex)
{
}
catch (Exception ex)
{
}
live-love
  • 48,840
  • 22
  • 240
  • 204

2 Answers2

3

Using UploadString and adding a header fixed the 400 error.

Then had to add the utf8 encoding parameter to fix a 500 error.

client.Headers.Add("Content-Type", "text/xml");
client.Encoding = Encoding.UTF8;
string response = client.UploadString(CRMIntegrationURL, "POST", xmlOutput);

    string s = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<Program xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"loyalty.xsd\">" +
    "</Program>";

    string test = client.UploadString(url, s);

Using Fiddler, I could see that the Requests types are different.

UploadFile:

Content-Disposition: form-data; name="file"; filename="test1.txt" Content-Type: text/xml

UploadString:

Content-Type: text/xml
live-love
  • 48,840
  • 22
  • 240
  • 204
0

I had the same problem with posting a text file of measurements to InfluxDB. The accepted answer helped a lot, but I also had to get rid of \r characters in the text content to eliminate the 400 Bad Request error. I don't know if this is a general rule for InfluxDB or if this is only the case when InfluxDB is installed on a unix system (Ubuntu in my case).

You can either set the line breaks before writing as described here: https://stackoverflow.com/a/7841819/5823275 or you can remove \r afterwards with text = text.Replace("\r", "");.

Chris Tophski
  • 930
  • 1
  • 6
  • 23