C# 模拟Http请求、下载
1.引入必须的命名空间:
using System.Net;
using System.IO;
2.模拟Http请求:
/// <summary> /// 发送post请求 /// </summary> /// <param name="Url">请求的url路径</param> /// <param name="postDataStr">参数</param> /// <returns>返回响应结果(字符串、json、xml)</returns> private string HttpPost(string _url, string _pms) { //创建request请求对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url); //请求方式 request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = Encoding.UTF8.GetByteCount(_pms); Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); myStreamWriter.Write(_pms); myStreamWriter.Close(); //创建response响应对象 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
public string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
3.模拟http下载:
/// <summary> /// 模拟http下载文件到本地 /// </summary> /// <param name="_url">下载链接</param> /// <param name="_localPath">本地存放地址</param> /// <returns>本地存放路径</returns> public static string HttpDownloadFile(string _url, string _localPath) { if(File.Exists(_localPath)){ return _localPath; } // 设置参数 HttpWebRequest request = WebRequest.Create(_url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 Stream stream = new FileStream(_localPath, FileMode.Create); byte[] byteArry = new byte[1024]; int size = responseStream.Read(byteArry, 0, (int)byteArry.Length); while (size > 0) { stream.Write(byteArry, 0, size); size = responseStream.Read(byteArry, 0, (int)byteArry.Length); } stream.Close(); responseStream.Close(); return _localPath; }
不积跬步,无以至千里;不积小流,无以成江海。ヾ(◍°∇°◍)ノ゙