WebClient以POST方式发送Web请求
来源:互联网 发布:php获取数组元素个数 编辑:程序博客网 时间:2024/06/07 18:04
本例使用WebClient以POST方式发送Web请求并下载一个文件,难点是postData的构造,发送Web请求时有的网站要求可能要求Cookies前后一致。其中application/x-www-form-urlencoded会告诉服务器该参数是以param1=value1¶m2=value2¶m3=value3方式拼接的。
private bool postDataandDownloadFile(string fileName){ string url = "http://www.huiyaosoft.com/test.aspx"; StringBuilder postData = new StringBuilder(); postData.AppendFormat("{0}={1}&", "username", "admin"); postData.AppendFormat("{0}={1}&", "password", "123456"); postData.AppendFormat("{0}={1}&", "nickname", UrlEncode("辉耀")); try { if (wc == null) wc = new System.Net.WebClient(); wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); // 继承Cookies if (!string.IsNullOrEmpty(cookies)) wc.Headers.Add("Cookie", cookies); // Upload the input string using the HTTP 1.0 POST method. byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData.ToString()); // 此处返回的是一个文件 byte[] byteResult = wc.UploadData(url, "POST", byteArray); // 取得Cookies cookies = wc.ResponseHeaders["Set-Cookie"]; if (type == 1 || type == 3) writeFile(byteResult, fileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return false;}
由于设置了"Content-Type"为"application/x-www-form-urlencoded",所以postData必须先进行urlencode。UrlEncode()的作用是将参数进行编码。
public string UrlEncode(string str){ byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); return System.Web.HttpUtility.UrlEncode(byStr);}
//写byte[]到fileName private bool writeFile(byte[] pReadByte, string fileName){ FileStream pFileStream = null; try { pFileStream = new FileStream(fileName, FileMode.OpenOrCreate); pFileStream.Write(pReadByte, 0, pReadByte.Length); } catch { return false; } finally { if (pFileStream != null) pFileStream.Close(); } return true;}
(完)
0 0
- WebClient以POST方式发送Web请求
- 以Post方式发送数据采用WebClient
- WebClient发送POST请求
- WebClient发送POST请求
- 以Post方式请求
- 以post方式发送链接请求的javascript函数
- .net后台webclient用post方式发送文件和数据
- Post方式发送Ajax请求
- 使用HttpWebRequest发送自定义POST请求(以http方式推送消息)
- IOS总结_IOS以post方式向PHP服务器端发送json数据请求
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- beego开发web服务+fiddler模拟Post请求+以json类型发送数据
- C# WebRequest WebClient Post请求
- httpclient以post方式发送body
- ajax以get和post方式请求
- Post方式发送http请求参数
- 快速批量提取文件夹中次级文件夹及文件名称的技巧
- 算法先锋队
- 【杭电oj4907】Task schedule
- 10007---敏捷开发实践(一)--谈谈我对敏捷开发的理解
- 我的前端之路(一)
- WebClient以POST方式发送Web请求
- Spring Boot 学习之旅
- 整理:std::sort源码剖析
- C++11之lock_guard学习总结和代码实例
- 148. Sort List
- 7.27 关于工具类 多态和继承的小记
- 使用 setuid、setgid 和 Sticky 位的特殊文件权限
- 单例设计模式(java版)
- java 线程终止方法