【问题标题】:WebClient UploadFile The remote server returned an error: (400) Bad RequestWebClient UploadFile 远程服务器返回错误:(400) Bad Request
【发布时间】:2014-07-02 20:50:12
【问题描述】:

尝试上传 xml 文件时,此特定服务器返回错误(上述异常)。 我在另一台服务器 (https://posttestserver.com/post.php) 上尝试了另一个 url,并且代码有效。 我的同事能够通过 Perl 脚本上传相同的 xml 文件。

我的问题是:还有其他方法可以上传文件的内容吗?试过UploadData,UploadString,还是一样的错误。

// 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)
{
}

【问题讨论】:

  • 您是否安装了fiddler 并检查了您发送的请求?

标签: c# system.net


【解决方案1】:

使用 UploadString 并添加标头修复了 400 错误。

然后不得不添加 utf8 编码参数来修复 500 错误。

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

使用 Fiddler,我可以看到请求类型不同。

上传文件:

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

上传字符串:

Content-Type: text/xml

【讨论】:

    【解决方案2】:

    我在将测量的文本文件发布到 InfluxDB 时遇到了同样的问题。接受的答案有很大帮助,但我还必须删除文本内容中的\r 字符以消除400 Bad Request 错误。我不知道这是否是 InfluxDB 的一般规则,或者仅当 InfluxDB 安装在 unix 系统(在我的情况下为 Ubuntu)上时才会出现这种情况。

    您可以在写入之前设置换行符,如下所述:https://stackoverflow.com/a/7841819/5823275 或者您可以在之后使用text = text.Replace("\r", ""); 删除\r

    【讨论】:

      猜你喜欢
      • 2010-12-13
      • 1970-01-01
      • 2013-04-20
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      相关资源
      最近更新 更多