using System; using System.Net; using System.IO; using System.Web; using System.Text; namespace myClass { public class clsWebSubmit { //向服务器送出 POST 请求 public string PostSubmit(string strUrl, string strParam) { string strResult = "error"; try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(strUrl); Encoding encoding = Encoding.UTF8; //encoding.GetBytes(postData); byte[] bs = Encoding.ASCII.GetBytes(strParam); string responseData = System.String.Empty; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = bs.Length; try { using (System.IO.Stream reqStream = req.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse()) { using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd().ToString(); strResult = responseData; } } } catch (System.Exception ex) { //strResult = "error:" + ex.Message;//返回异常信息 strResult = ""; clsLogHelper.m_CreateErrorLogTxt("m_PostSubmit ", strUrl + " " + strParam, ex.Message); } } catch (System.Exception ex) { //strResult = "error:" + ex.Message;//返回异常信息 strResult = ""; clsLogHelper.m_CreateErrorLogTxt("m_PostSubmit ", strUrl + " " + strParam, ex.Message); } return strResult; #region 这个写法写好用 /* 这个写法写好用 ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(strParam); HttpWebRequest request =(HttpWebRequest)HttpWebRequest.Create(this.url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; Stream sm = request.GetRequestStream(); sm.Write(data, 0, data.Length); sm.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode.ToString() != "OK") { //MessageBox.Show(response.StatusDescription.ToString()); return "error"; } StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = myreader.ReadToEnd(); string str = System.Web.HttpUtility.UrlEncode(responseText, Encoding.UTF8); return str; */ #endregion } //向服务器送出 POST 请求 这个写法写好用 public string PostSubmit2(string strUrl, string strParam) { string strResult = "error"; try { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(strParam); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; Stream sm = request.GetRequestStream(); sm.Write(data, 0, data.Length); sm.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode.ToString() != "OK") { //MessageBox.Show(response.StatusDescription.ToString()); return "error"; } StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); strResult = myreader.ReadToEnd(); //string str = System.Web.HttpUtility.UrlEncode(strResult, Encoding.UTF8); return strResult; } catch (System.Exception ex) { strResult = "error:" + ex.Message;//返回异常信息 clsLogHelper.m_CreateErrorLogTxt("m_PostRequest ", strUrl + " " + strParam, ex.Message); return strResult; } } //创建 Post 的HTTP请求 带Json参数的 public string PostRequest(string url, string headerToken, string strParam) { try { //string strParam = "{\"destNumber\":\"" + strExtTel + "\", \"app\":\"transfer\",\"args\":\"" + strCalledNumber + "\"}"; //String strUrl = "http://192.168.1.31:80/api/channels"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; //request.ContentType = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; request.Headers["X-XTRA-AUTH-ID"] = headerToken; //添加头 //参数 ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(strParam); request.ContentLength = data.Length; Stream sm = request.GetRequestStream(); sm.Write(data, 0, data.Length); sm.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream rs = response.GetResponseStream(); //StreamReader sr = new StreamReader(rs, encode); StreamReader sr = new StreamReader(rs, Encoding.UTF8); var result = sr.ReadToEnd(); sr.Close(); rs.Close(); return result; } catch (Exception ex) { myClass.clsLogHelper.m_CreateErrorLogTxt("clsWebSubmit", "PostRequest()", ex.Message.ToString()); return "-1"; } } //向服务器送出 Get 请求 public string GetSubmit(string strUrl, string strParam) { System.Net.HttpWebRequest request; // 创建一个HTTP请求 request = (System.Net.HttpWebRequest)WebRequest.Create(strUrl); request.Method="get"; System.Net.HttpWebResponse response; response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = myreader.ReadToEnd(); myreader.Close(); return responseText; } //创建GET的HTTP请求 //public string GetData(string url, Encoding encode) public string GetRequest(string url, string headerToken) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //request.ContentType = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; request.Headers["X-XTRA-AUTH-ID"] = headerToken; //添加头 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream rs = response.GetResponseStream(); //StreamReader sr = new StreamReader(rs, encode); StreamReader sr = new StreamReader(rs, Encoding.UTF8); var result = sr.ReadToEnd(); sr.Close(); rs.Close(); return result; } #region HTTP GET 请求示例 /* private void butGet_Click(object sender, EventArgs e) { string strURL = "http://localhost/WinformSubmit.php?tel=11111&name=张三"; System.Net.HttpWebRequest request; // 创建一个HTTP请求 request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); //request.Method="get"; System.Net.HttpWebResponse response; response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = myreader.ReadToEnd(); myreader.Close(); //MessageBox.Show(responseText); this.txtResult.Text = responseText; } */ #endregion #region HTTP GET 请求示例 /* private void butPost_Click(object sender, EventArgs e) { string strURL = "http://localhost/WinformSubmit.php"; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); //Post请求方式 request.Method = "POST"; // 内容类型 request.ContentType = "application/x-www-form-urlencoded"; // 参数经过URL编码 string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword"); paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("多月"); byte[] payload; //将URL编码后的字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); //设置请求的 ContentLength request.ContentLength = payload.Length; //获得请 求流 System.IO.Stream writer = request.GetRequestStream(); //将请求参数写入流 writer.Write(payload, 0, payload.Length); // 关闭请求流 writer.Close(); System.Net.HttpWebResponse response; // 获得响应流 response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = myreader.ReadToEnd(); myreader.Close(); //MessageBox.Show(responseText); this.txtResult.Text = responseText; } */ #endregion } }
调用方式示例
string strUrl = "http://localhost/WinformSubmit.php"; //string param = string.Format("do=login&u={0}&p={1}", username, password); //参数的另一种写法 string strParam = "callerid=" + strCallerId;
clsWebSubmit myPost = new clsWebSubmit();
string strResult = myPost.PostSubmit(strUrl, strParam);
return strResult;
示例2 Post请求 带Json参数
string strParam = "{\"destNumber\":\"" + strExtTel + "\", \"app\":\"transfer\",\"args\":\"" + strCalledNumber + "\"}"; String strUrl = "http://192.168.1.31:80/api/channels"; clsWebSubmit myPost = new clsWebSubmit(); string strResultString = myPost.PostRequest(strUrl, strToken,strParam); return strResultString;
示例3 Get请求 带头部 Token
String strUrl = "http://192.168.1.31:80/api/users/list"; clsWebSubmit myPost = new clsWebSubmit(); string strResultString = myPost.GetRequest(strUrl, strToken); return strResultString;
标签:Http,string,Get,C#,request,System,StreamReader,HttpWebRequest,response From: https://www.cnblogs.com/hailexuexi/p/16895404.html