Get方法
public string HttpGet(string Url, string param) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (param == "" ? "" : "?") + param); request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; 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; }
//使用示例 HttpGet("http://192.168.2.100/xxx", "SchoolID=S27-511-AF57&UserID=S001")
Post方法
Post请求是通过请求头(headers)的 Content-Type 字段值来描述其消息主体的编码方式,在日常开发中以下3种编码方式比较常见的:
- application/x-www-form-urlencoded
- application/json;charset=UTF-8
- multipart/form-data
其他详细的 Content-Type 讲解可以参考这篇文章 四种常见的 POST 提交数据方式 专题
所以,使用 HttpWebRequest 发送请求POST的 “姿势”(数据格式),会因为消息主体的编码方式的不同而有所差异。
1、application/x-www-form-urlencoded
public string HttpPost(string url, string param) { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); Encoding encoding = Encoding.UTF8; byte[] byteArray = Encoding.UTF8.GetBytes(param); string responseData = String.Empty; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = byteArray.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(byteArray, 0, byteArray.Length); } using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd(); } return responseData; } }
//使用示例 HttpPost("http://192.168.2.100/xxx", "SchoolID=S27-511-AF57&UserID=S001")
2、application/json;charset=UTF-8
public string HttpPost(string url, Dictionary<string, object> param) { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); Encoding encoding = Encoding.UTF8; byte[] byteArray = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(param)); string responseData = String.Empty; req.Method = "POST"; req.ContentType = "application/json;charset=UTF-8"; req.ContentLength = byteArray.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(byteArray, 0, byteArray.Length); } using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd(); } return responseData; } }
//使用示例
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("SchoolID", "S27-511-AF57");
param.Add("UserID", "S001");
HttpPost("http://192.168.2.100/xxx", param);
3、multipart/form-data ,一般用来上传文件
public string HttpPost(string url, string file) { //边界 string boundary = DateTime.Now.Ticks.ToString("x"); HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(url);//url为上传的地址 uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary; uploadRequest.Method = "POST"; uploadRequest.Accept = "*/*"; uploadRequest.KeepAlive = true; uploadRequest.Headers.Add("Accept-Language", "zh-cn"); uploadRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); uploadRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; //uploadRequest.Headers["Cookie"] = cookies;//上传文件时需要的cookies WebResponse response; string responseData = String.Empty; //创建一个内存流 Stream memStream = new MemoryStream(); //确定上传的文件路径 if (!String.IsNullOrEmpty(file)) { boundary = "--" + boundary; //添加上传文件参数格式边界 string paramFormat = boundary + " Content-Disposition: form-data; name="{0}"; {1} "; NameValueCollection param = new NameValueCollection(); param.Add("fname", Guid.NewGuid().ToString() + Path.GetExtension(file)); //写上参数 foreach (string key in param.Keys) { string formitem = string.Format(paramFormat, key, param[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } //添加上传文件数据格式边界 string dataFormat = boundary + " Content-Disposition: form-data; name="{0}";filename="{1}" Content-Type:application/octet-stream "; string header = string.Format(dataFormat, "Filedata", Path.GetFileName(file)); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); //获取文件内容 FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; //将文件内容写进内存流 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } fileStream.Close(); //添加文件结束边界 byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes(" " + boundary + " Content-Disposition: form-data; name="Upload" Submit Query " + boundary + "--"); memStream.Write(boundarybytes, 0, boundarybytes.Length); //设置请求长度 uploadRequest.ContentLength = memStream.Length; //获取请求写入流 Stream requestStream = uploadRequest.GetRequestStream(); //将内存流数据读取位置归零 memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); //将内存流中的buffer写入到请求写入流 requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); } //获取到上传请求的响应 response = uploadRequest.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { responseData = reader.ReadToEnd(); } return responseData; }
此方法出处
作者:Louja
原址:https://www.cnblogs.com/loujady/archive/2011/09/13/2174695.html