使用 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 ...
随机推荐
- VMware安装完后,没有虚拟网卡
1 问题描述: 1.1 windows10首次安装VMware,或者非首次安装VMware时,安装后,没有出现如下图所示的虚拟网卡: 1.2 Xshell或者SecureCRT 或者editplus等 ...
- SQLSERVER中常用的系统视图
QLServer中提供了相当丰富的系统视图,能够从宏观到微观,从静态到动态反应数据库对象的存储结果.系统性能.系统等待事件等等.同时 也保留了与早期版本兼容性的视图,主要差别在于SQLServer20 ...
- Java多线程—JUC原子类
根据修改的数据类型,可以将JUC包中的原子操作类可以分为4类. 1. 基本类型: AtomicInteger, AtomicLong, AtomicBoolean ;2. 数组类型: AtomicIn ...
- 基于jquery的ajax方法封装
在实际的项目里,ajax的应用频率很高,所以尽管jquery或者其他的一些类似的js库做了非常不错的封装,仍然有进一步封装简化的空间和必要 举一个例子,很久很久以前,我的ajax是这么写的: $.aj ...
- strlen头文件
#include <string.h> 函数strlen strsep 等等
- IO引脚复用和映射
1.端口复用 这些外设包括ADC,DAC以及串口等等. 查找STM32F429数据手册可以找到相关IO口的复用功能引脚. 注意:除ADC和DAC要配置成模拟通道外,其他的所有外设都要配置成复用功能.
- OSG图形设备接口GraphicsContext
1.图形设备与相机 在Camera类的成员函数中,setGraphicContext()函数的工作是设置相机对应的图形设备对象,换句话说,下面要介绍的GraphicsContext类就是图形设备对象的 ...
- spring-boot-maven-plugin插件作用
转自:http://blog.csdn.net/hotdust/article/details/51404828 OM 文件中添加了“org.springframework.boot:spring-b ...
- Android开发之Tween(补间动画)
在android中动画主要有三种,①帧动画(http://blog.csdn.net/dmk877/article/details/45893017)这篇文章已经详细的进行了讲解,②补间动画这也是这篇 ...
- DRBD 数据镜像软件
1>DRBD介绍 1>数据镜像软件DRBD介绍 分布式块设备复制(Distributed Relicated Block Deivce,DRBD),是一种基于软件.基于网络的块复制存储解 ...