簡體   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