[英]Uploading file via WebClient
我必須將文件(使用我之前的代碼生成的XML)上載到一個提供以下信息的Web服務:
網址( http://www.example.com/upload
)
端口(1234)
方法(POST或PUT)
因此,我在這里進行了很多搜索,發現使用WebClient的一些代碼似乎可以滿足我的需求。
try
{
using (WebClient webclient = new WebClient())
{
byte[] rawResponse = webclient.UploadFile(httpUrl, xmlNewFile);
Console.WriteLine("Remote Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse));
Console.ReadLine();
}
}
catch (Exception ex)
{
uploadError = true;
}
我的httpUrl看起來像http://www.example.com:1234/upload
。
問題是在使用UploadFile命令運行該行后,我立即得到一個第一次機會異常(“ System.dll中發生了類型'System.Net.WebException'的第一次機會異常”)。 我可以使用瀏覽器在給定端口上打開給定URL,所以連接本身不應該成為問題。
有什么想法可以從哪里開始搜索引起的錯誤嗎? 謝謝!
編輯:好的,感謝你們,現在我知道我從服務器收到錯誤。
System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
at System.Net.WebClient.UploadFile(String address, String fileName)
at XML_Export.Program.Main(String[] args) in Program.cs:line 177
有趣的是,我的瀏覽器顯示“ 200 OK”。
您必須檢查被拋出的異常。 我通常以這種方式登錄
try
{
//some cool stuff with webClient
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var s = reader.ReadToEnd();
throw new Exception(s, ex);
}
}
catch (Exception e)
{
throw e;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.