使用 WebClient 來存取 GET,POST,PUT,DELETE,PATCH 網路資源
WebClient 基本資訊
提供通用方法使用 WebRequest 類別傳送及接收 URI (支援 http:, https:, ftp:,和 file: ) 的資源
- Namespace:System.Net
- Assembly:System (System.dll)
- 基本要求:.NET Framework 1.1 以上
- WebClient 預設僅會傳送必要的 http header
- 缺點:無法指定 Timeout ,另外保哥文章 利用 WebClient 類別模擬 HTTP POST 表單送出的注意事項有提到
不適合用來下載大量的檔案,高負載的網站也不適合這樣用,即便你用非同步的方式撰寫,也會讓 WebClient 因為佔據過多 Threads 而導致效能降低這我不知道怎麼模擬,請大家參考保哥文章
1. GET
- 寫法 1
using (WebClient webClient = new WebClient())
// 從 url 讀取資訊至 stream
using(Stream stream = webClient.OpenRead("http://jsonplaceholder.typicode.com/posts"))
// 使用 StreamReader 讀取 stream 內的字元
using(StreamReader reader= new StreamReader(stream))
{
// 將 StreamReader 所讀到的字元轉為 string
string request = reader.ReadToEnd();
request.Dump();
} - 寫法 2
// 建立 webclient
using(WebClient webClient = new WebClient())
{
// 指定 WebClient 的編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// 從網路 url 上取得資料
var body = webClient.DownloadString("http://jsonplaceholder.typicode.com/posts");
body.Dump();
}
2. POST
WebClient 共有四種 POST 相關的方法
- UploadString(string)
將 String 傳送至資源。
- 以下 demo 會搭配
application/json// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {apitoken}");
// 準備寫入的 data
PostData postData = new PostData() { userId = 1123456, title = "yowko", body = "yowko test body 中文" };
// 將 data 轉為 json
string json = JsonConvert.SerializeObject(postData);
// 執行 post 動作
var result = webClient.UploadString("https://jsonbin.org/yowko/test", json);
// linqpad 將 post 結果輸出
result.Dump();
}
- 以下 demo 會搭配
- UploadData(byte[])
將位元組陣列傳送至資源,並傳回含有任何回應的 Byte 陣列。
- 以下 demo 會搭配
application/x-www-form-urlencoded// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {apitoken}");
//要傳送的資料內容(依字串表示)
string postData = "id=12354&name=yowko&body=yowko test body 中文";
//將傳送的字串轉為 byte array
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// 執行 post 動作
var result = webClient.UploadData("https://jsonbin.org/yowko/test", byteArray);
// linqpad 將 post 結果輸出
result.Dump();
}
- 以下 demo 會搭配
- UploadValues (byte[])
將 NameValueCollection 傳送至資源,並傳回含有任何回應的 Byte 陣列。
- 不需指定 content type
// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {apitoken}");
//要傳送的資料內容
NameValueCollection nameValues = new NameValueCollection();
nameValues["userId"] = "456";
nameValues["title"] = "yowko";
nameValues["body"]="yowko test body 中文"; // 執行 post 動作
var result = webClient.UploadValues("https://jsonbin.org/yowko/test", nameValues);
//將 post 結果轉為 string
string resultstr = Encoding.UTF8.GetString(result);
// linqpad 將 post 結果輸出
resultstr.Dump();
}
- 不需指定 content type
- UploadFile(byte[]) 今天不會介紹
將本機檔案傳送至資源,並傳回含有任何回應的 Byte 陣列。
3. PUT
方法與 POST 相同,只需在 url 與 data 間多傳一個 method 的參數,範例中 PUT 是將 jsonbin 的網址改為 public
// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {apitoken}");
// 執行 PUT 動作
var result = webClient.UploadString("https://jsonbin.org/yowko/test/_perms","PUT", "");
// linqpad 將 post 結果輸出
result.Dump();
}
5. DELETE
方法與 POST 相同,只需在 url 與 data 間多傳一個 method 的參數,範例中 DELETE 是將 jsonbin 的網址改為 private
// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {apitoken}");
// 執行 DELETE 動作
var result = webClient.UploadString("https://jsonbin.org/yowko/test/_perms","DELETE", "");
// linqpad 將 post 結果輸出
result.Dump();
}
6. PATCH
方法與 POST 相同,只需在 url 與 data 間多傳一個 method 的參數
// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {api token}");
// 準備寫入的 data
PostData postData = new PostData() { title = "yowko 中文", body = "yowko body 中文" };
// 將 data 轉為 json
string json = JsonConvert.SerializeObject(postData);
// 執行 PATCH 動作
var result = webClient.UploadString("https://jsonbin.org/yowko/test","PATCH", json);
// linqpad 將 post 結果輸出
result.Dump();
}
7. 使用 proxy
有時候程式的 host 環境無法直接上網或是我們想要確認傳出去的相關資訊,就需要設定 proxy
// 建立 WebClient
using (WebClient webClient = new WebClient())
{
// 指定 WebClient 編碼
webClient.Encoding = Encoding.UTF8;
// 指定 WebClient 的 Content-Type header
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// 指定 WebClient 的 authorization header
webClient.Headers.Add("authorization", "token {api token}");
//指令 proxy address
string proxyAddress = "http://127.0.0.1:8888";
//建立 proxy
WebProxy myProxy = new WebProxy(new Uri(proxyAddress));
//建立 proxy 的認證資訊
myProxy.Credentials = new NetworkCredential("{username}", "{password}");
//將 proxy 指定給 request 使用
webClient.Proxy = myProxy;
// 準備寫入的 data
PostData postData = new PostData() { userId=1, title = "yowko1", body = "yowko test body 中文" };
// 將 data 轉為 json
string json = JsonConvert.SerializeObject(postData);
// 執行 post 動作
var result = webClient.UploadString("https://jsonbin.org/yowko/test", json);
// linqpad 將 post 結果輸出
result.Dump();
}
- 以 fiddler 為例
- fiddler 的相關設定請參考 使用 fiddler 內建 proxy 來截錄手機或是程式封包
- 截錄到的內容

參考資料
使用 WebClient 來存取 GET,POST,PUT,DELETE,PATCH 網路資源的更多相关文章
- [Xamarin] 透過WebClient跟網路取得資料 (转帖)
之前寫過一篇文章,關於在Android上面取得資料 透過GET方式傳資料給Server(含解決中文編碼問題) 我們來回顧一下 Android 端的Code: 有沒有超多,如果是在Xaramin下面,真 ...
- [技术博客]OKhttp3使用get,post,delete,patch四种请求
OKhttp3使用get,post,delete,patch四种请求 1.okhttp简介 okhttp封装了大量http操作,大大简化了安卓网络请求操作,是现在最火的安卓端轻量级网络框架.如今okh ...
- 精讲响应式WebClient第3篇-POST、DELETE、PUT方法使用
本文是精讲响应式WebClient第3篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...
- PHP用curl发送get post put delete patch请求
function getUrl($url){ $headerArray = array("Content-type:application/json;", "Accept ...
- ORA-00054: 資源正被使用中, 請設定 NOWAIT 來取得它, 否則逾時到期
1.查看被使用资源的OBJECT_ID SELECT *FROM DBA_OBJECTS WHERE OBJECT_NAME='OBJECT_NAME' 2.查看资源被谁占用SELECT * FROM ...
- 使用WebClient與HttpWebRequest的差異
在<Windows Phone 7-下載檔案至Isolated Storage>提到了透過WebClient的功能將網站上的檔案下載至 WP7的Isoated Storage之中.但實際的 ...
- WebApi:WebApi的Self Host模式
不用IIS也能執行ASP.NET Web API 转载:http://blog.darkthread.net/post-2013-06-04-self-host-web-api.aspx 在某些情境, ...
- Self-Host c#学习笔记之Application.DoEvents应用 不用IIS也能執行ASP.NET Web API
Self-Host 寄宿Web API 不一定需要IIS 的支持,我们可以采用Self Host 的方式使用任意类型的应用程序(控制台.Windows Forms 应用.WPF 应用甚至是Wind ...
- VMware虛擬化技術實作問答
http://www.netadmin.com.tw/article_content.aspx?sn=1202130002&ns=1203280001&jump=3 Q4:啟用VMwa ...
随机推荐
- xdebug 一直报错 upstream timed out (110: Connection timed out) while reading response header from upstream
本地主机(Windows环境192.168.66.1)访问虚拟机(192.168.66.139)里面的搭建的php环境(系统centos6.5版本,php版本是5.5.30 ,xdebug 2.4.0 ...
- Linux分区挂载点介绍
一.Linux分区挂载点介绍 Linux分区挂载点介绍,推荐容量仅供参考不是绝对,跟各系统用途以及硬盘空间配额等因素实际调整: 分区类型 介绍 备注 /boot 启动分区 一般设置100M-200M, ...
- code1796 社交网络
输入描述 Input Description 输入文件中第一行有两个整数,n 和 m,表示社交网络中结点和无向边的数 目.在无向图中,我们将所有结点从 1 到 n 进行编号. 接下来 m 行,每行用三 ...
- strtotime()
date('Y-m-d H:i:s',time()) //24小时 date('Y-m-d h:i:s',time()) //12小时
- networkX用法整
无向图,有向图,加权图等例子代码 [http://www.cnblogs.com/kaituorensheng/p/5423131.html#_label1] 数据分析学习笔记(三)-NetworkX ...
- Linux编程实现蜂鸣器演奏康定情歌
Linux编程实现蜂鸣器演奏康定情歌 摘自:https://blog.csdn.net/jiazhen/article/details/3490979 2008年12月10日 15:40:00 j ...
- ethtool -p eth0 物理口一个灯在不停的闪烁
摘自:https://blog.csdn.net/morigejile/article/details/78598645 你的 服务器有多个网卡并且已经配置好运行当中,你却没记得eth0.eth1. ...
- YII2 选择布局
方案1:控制器内成员变量 public $layout = false; //不使用布局 public $layout = "main"; //设置使用的布局文件 方案2:控制器成 ...
- 特征工程 vs. 特征提取
“特征工程”这个华丽的术语,它以尽可能容易地使模型达到良好性能的方式,来确保你的预测因子被编码到模型中.例如,如果你有一个日期字段作为一个预测因子,并且它在周末与平日的响应上有着很大的不同,那么以这种 ...
- JavaScript语言精粹 笔记05 正则表达式
正则表达式 正则表达式以方法的形式被用于对字符串中的信息进行查找.替换画图提取操作.可处理正则表达式的方法有:regexp.exec, regexp.test,string.match, string ...