2014-09-19 87 views
0

我有上传文件(即一直与我以前的代码生成的XML)来给了我以下信息的Web服务:上传文件

URL(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.Net.WebException”在System.dll中发生的第一个机会异常)。 我可以使用浏览器打开给定端口上的给定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”......嗯。

+1

什么是来自'WebException'的消息?如果你看看'http:// www.example.com/upload',表单是否发布到另一个位置? – mason 2014-09-19 14:31:04

+3

提示:捕捉一个异常并且不做任何事情,甚至不记录它,但很少是一个好主意。 – 2014-09-19 14:33:54

+0

在我的浏览器中的httpUrl给了我一个白页“HTTP/1.1 200 OK日期:19.09.2014 TIME:16:32:58 CET”。 好吧,我将不得不尝试如何记录异常 - 给我几分钟。 – 2014-09-19 14:35:53

回答

0

你必须检查trown的异常。我通常以这种方式登录

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