繁体   English   中英

WebClient UploadFile远程服务器返回错误:(400)错误的请求

[英]WebClient UploadFile The remote server returned an error: (400) Bad Request

尝试上传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)
{
}

使用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,我可以看到Requests类型是不同的。

上传文件:

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

UploadString:

Content-Type: text/xml

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

您可以按照下面的描述在写之前设置换行符: https : text = text.Replace("\\r", "");或者之后可以使用text = text.Replace("\\r", "");删除\\r text = text.Replace("\\r", "");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM