Post fields and a file using the new System.Net.We

2019-05-31 14:13发布

i'm trying to invoke a webapi with the new System.Net.WebClient and didnot found any special examples.

The goal is simulate a traditional form post with some fields and a file.

how can i do it using the System.Net.WebClient or where can i find some examples?

thanks in advance

2条回答
一纸荒年 Trace。
2楼-- · 2019-05-31 14:49

There are a lot of examples if you do a fast google search, anyway, here goes some samples:

Simple GET

WebClient webClient = new WebClient();
webClient.Headers["Accept"] = "application/json"; //setting headers

string json = webClient.DownloadString(url);

Simple POST

NameValueCollection values = new NameValueCollection();
values["user"] = username;
values["pwd"] = password;
webClient.UploadValues(url, values);

There's also an UploadData that sends byte arrays and UploadFile that allows you to upload files directly from disk.

查看更多
We Are One
3楼-- · 2019-05-31 14:58

I think you need this:

http://dzimchuk.net/post/uploading-a-file-over-http-in-net

This is a very well written blog. See the last example.

查看更多
登录 后发表回答