(HttpWebRequest模拟请求登录):当一些硬件设备接口 或需要调用其他地方的接口时,模拟请求登录获取接口的数据就很有必要。
webclient类:只想从特定的URI请求文件,则使用WebClient;
1.创建带Cookie的webclient:
/// <summary> /// 带 Cookie 的 WebClient /// </summary> public class CookieWebClient : WebClient { // Cookie 容器 public CookieContainer Cookies; /// <summary> /// 创建一个新的 CookieWebClient 实例。 /// </summary> public CookieWebClient() { this.Cookies = new CookieContainer(); } protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); if (request is HttpWebRequest) { HttpWebRequest httpRequest = request as HttpWebRequest; httpRequest.CookieContainer = Cookies; } return request; } }
2.http方法(Get、POST):
public CookieContainer cookies; internal string HttpGet(string Url) { string result = ""; using (var client = new CookieWebClient()) { client.Encoding = Encoding.UTF8; client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded,charset=UTF-8"; client.Cookie = cookies; byte[] data = client.DownloadData(Url); result = Encoding.UTF8.GetString(data); } return result; } internal string HttpPost(string Url, string postDataStr) { string result = ""; using (var client = new CookieWebClient()) { client.Encoding = Encoding.UTF8; client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8"; byte[] post = Encoding.UTF8.GetBytes(postDataStr); byte[] data = client.UploadData(Url,post); result = Encoding.UTF8.GetString(data); cookies = client.Cookie; } return result; }
3. controller
[HttpGet] public string Getinfo(string name, string pwd) { string hg = ""; string url = "http://111.38.56.130:8084/LoginHandler.ashx?time=" + DateTime.Now; string loginp = "action=Login&flag=1&name={0}&pwd={1}&isRemember=false"; string urlget = "http://111.38.56.130:8084/Company/IndexHandler.ashx?time={0}&action=deviceShowData&greenHouseSerialNum=00000F003G001"; string param = string.Format(loginp, name, pwd); exta.http h = new exta.http(); string r = h.HttpPost(url, param); if (r.Equals("0")) { hg = h.HttpGet(string.Format(urlget, DateTime.Now)); } return hg; }