【C#】.net 发送get/post请求
基础学习
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// Http (GET/POST) /// </summary> /// <param name="url">请求URL</param> /// <param name="parameters">请求参数</param> /// <param name="method">请求方法</param> /// <returns>响应内容</returns> static string sendPost(string url, IDictionary<string, string> parameters, string method) { if (method.ToLower() == "post") { HttpWebRequest req = null; HttpWebResponse rsp = null; System.IO.Stream reqStream = null; try { req = (HttpWebRequest)WebRequest.Create(url); req.Method = method; req.KeepAlive = false; req.ProtocolVersion = HttpVersion.Version10; req.Timeout = 5000; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8")); reqStream = req.GetRequestStream(); reqStream.Write(postData, 0, postData.Length); rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); return GetResponseAsString(rsp, encoding); } catch (Exception ex) { return ex.Message; } finally { if (reqStream != null) reqStream.Close(); if (rsp != null) rsp.Close(); } } else { //创建请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8")); //GET请求 request.Method = "GET"; request.ReadWriteTimeout = 5000; 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(); return retString; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public HttpWebRequest GetWebRequest(string url, string method) { HttpWebRequest request = null; if (url.Contains("https")) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult); request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); } else { request = (HttpWebRequest)WebRequest.Create(url); } request.ServicePoint.Expect100Continue = false; request.Method = method; request.KeepAlive = true; request.UserAgent = "stgp"; return request; } /// <summary> /// 解决使用上面方法向同一个地址发送请求时会发生:基础连接已经关闭: 服务器关闭了本应保持活动状态的连接的问题 /// </summary> /// <param name="url"></param> /// <param name="method"></param> /// <returns></returns> public HttpWebRequest GetWebRequestDotnetReference(string url, string method) { HttpWebRequest request = null; if (url.Contains("https")) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult); request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); } else { request = (HttpWebRequest)WebRequest.Create(url); } request.Method = method; request.KeepAlive = false;//fase request.ProtocolVersion = HttpVersion.Version11;//Version11 request.UserAgent = "stgp"; return request; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 组装普通文本请求参数。 /// </summary> /// <param name="parameters">Key-Value形式请求参数字典</param> /// <returns>URL编码后的请求数据</returns> static string BuildQuery(IDictionary<string, string> parameters, string encode) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略参数名或参数值为空的参数 if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); if (encode == "gb2312") { postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312"))); } else if (encode == "utf8") { postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8)); } else { postData.Append(value); } hasParam = true; } } return postData.ToString(); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 把响应流转换为文本。 /// </summary> /// <param name="rsp">响应流对象</param> /// <param name="encoding">编码方式</param> /// <returns>响应文本</returns> static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { System.IO.Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
string url = "http://www.example.com/api/exampleHandler.ashx"; var parameters = new Dictionary<string, string>(); parameters.Add("param1", "1"); parameters.Add("param2", "2"); string result = sendPost(url, parameters, "get");
进阶学习
一、读取本地图片文件,进行上传
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public string DoPostWithFile(string url, IDictionary<string, string> textParams, List<string> filePathList, string charset = "utf-8") { string boundary = "-------" + DateTime.Now.Ticks.ToString("X"); // 随机分隔线 HttpWebRequest req = GetWebRequestDotnetReference(url, "POST"); req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary; System.IO.Stream reqStream = req.GetRequestStream(); byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n"); // 组装文本请求参数 string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}"; IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator(); while (textEnum.MoveNext()) { string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value); byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry); reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); reqStream.Write(itemBytes, 0, itemBytes.Length); } // 组装文件请求参数 #region 将文件转成二进制 string fileName = string.Empty; byte[] fileContentByte = new byte[1024]; string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\n\r\n"; foreach (string filePath in filePathList) { fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1); FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); fileContentByte = new byte[fs.Length]; fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length)); fs.Close(); string fileEntry = string.Format(fileTemplate, "images[]", fileName); byte[] itemBytesF = Encoding.GetEncoding(charset).GetBytes(fileEntry); reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); reqStream.Write(itemBytesF, 0, itemBytesF.Length); reqStream.Write(fileContentByte, 0, fileContentByte.Length); } #endregion reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); return GetResponseAsString(rsp, encoding); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
string url = "http://www.example.com/api/exampleHandler.ashx"; var param = new Dictionary<string, string>(); param.Add("param1", "1"); List<string> filePathList = new List<string>(); filePathList.Add(@"C:\Users\pic1.png"); string result = DoPostWithFile(url, param, filePathList);
二、读取网络上的图片文件,进行上传
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public string DoPostWithNetFile(string url, IDictionary<string, string> textParams, List<string> filePathList, string charset = "utf-8") { string boundary = "-------" + DateTime.Now.Ticks.ToString("X"); // 随机分隔线 //HttpWebRequest req = GetWebRequest(url, "POST"); HttpWebRequest req = GetWebRequestDotnetReference(url, "POST"); req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary; System.IO.Stream reqStream = req.GetRequestStream(); byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n"); // 组装文本请求参数 string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}"; IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator(); while (textEnum.MoveNext()) { string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value); byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry); reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); reqStream.Write(itemBytes, 0, itemBytes.Length); } // 组装文件请求参数 #region 将文件转成二进制 string fileName = string.Empty; byte[] fileContentByte = new byte[1024]; string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\n\r\n"; foreach (string filePath in filePathList) { fileName = filePath.Substring(filePath.LastIndexOf(@"/") + 1); HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(filePath); imgRequest.Method = "GET"; using (HttpWebResponse imgResponse = imgRequest.GetResponse() as HttpWebResponse) { if (imgResponse.StatusCode == HttpStatusCode.OK) { Stream rs = imgResponse.GetResponseStream(); MemoryStream ms = new MemoryStream(); const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = rs.Read(buffer, 0, bufferLen)) > 0) { ms.Write(buffer, 0, count); } ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream fileContentByte = new byte[buffsize]; ms.Read(fileContentByte, 0, buffsize); ms.Flush(); ms.Close(); rs.Flush(); rs.Close(); } } string fileEntry = string.Format(fileTemplate, "images[]", fileName); byte[] itemBytesF = Encoding.GetEncoding(charset).GetBytes(fileEntry); reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); reqStream.Write(itemBytesF, 0, itemBytesF.Length); reqStream.Write(fileContentByte, 0, fileContentByte.Length); } #endregion reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); return GetResponseAsString(rsp, encoding); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
string url = "http://www.example.com/api/exampleHandler.ashx"; var param = new Dictionary<string, string>(); param.Add("param1", "1"); List<string> filePathList = new List<string>(); filePathList.Add(@"http://www.example.com/img/pic1.png"); string result = DoPostWithNetFile(url, param, filePathList);