简体   繁体   English

通过WebClient上传文件

[英]Uploading file via WebClient

I've got to upload a file (XML that's been generated with my previous code) to a web service that gave me following information: 我必须将文件(使用我之前的代码生成的XML)上载到一个提供以下信息的Web服务:

URL ( http://www.example.com/upload ) 网址( http://www.example.com/upload
Port (1234) 端口(1234)
Method (POST or PUT) 方法(POST或PUT)

So I searched a lot over here and found some code using WebClient that seemed to do just what I needed. 因此,我在这里进行了很多搜索,发现使用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;
}

My httpUrl looks like http://www.example.com:1234/upload . 我的httpUrl看起来像http://www.example.com:1234/upload

Problem is I'm getting a first chance exception ("A first chance exception of type 'System.Net.WebException' occurred in System.dll") immediately after running the line with the UploadFile command. 问题是在使用UploadFile命令运行该行后,我立即得到一个第一次机会异常(“ System.dll中发生了类型'System.Net.WebException'的第一次机会异常”)。 I can open the given URL on the given port with my browser, so the connection itself shouldn't be the problem. 我可以使用浏览器在给定端口上打开给定URL,所以连接本身不应该成为问题。

Any ideas where to begin my search for the causing error? 有什么想法可以从哪里开始搜索引起的错误吗? Thanks! 谢谢!

EDIT: Ok, thanks to you guys now I know that I get an error from the server. 编辑:好的,感谢你们,现在我知道我从服务器收到错误。

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

Funny thing is I get a "200 OK" with my browser... Hm. 有趣的是,我的浏览器显示“ 200 OK”。

You have to examine the exception being trown. 您必须检查被抛出的异常。 I usually log it in this way 我通常以这种方式登录

    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.

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