public class RestClientMethod { /// <summary> /// 请求服务器地址 /// </summary> public string BaseUri; //例如: http://10.0.0.193 public RestClientMethod(string baseUri) { this.BaseUri = baseUri; } /// <summary> /// Get请求 /// </summary> /// <param name="uri"></param> /// <param name="strAuth_token"></param> /// <returns></returns> public string Get(string uri, string strAuth_token) { string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri); //先根据用户请求的uri构造请求地址 HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl); //创建访问对象 myRequest.Headers.Add("Authorization", strAuth_token); //需要auth_token验证时添加,没有可去掉,下同 HttpWebResponse myResponse; //通过访问对象获取响应内容 try { myResponse = (HttpWebResponse)myRequest.GetResponse(); } catch (WebException ex) { myResponse = (HttpWebResponse)ex.Response; Console.WriteLine(ex.Response); } StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题 string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 //reader提供多种数据转换类型,如reader.ReadAsync可转换为所设定的实体类型 reader.Close(); myResponse.Close(); return returnXml; } #region Post请求 /// <summary> /// 登录获取权限POST底层方法 /// </summary> /// <param name="data">数据参数</param> /// <param name="uri">API接口path</param> /// <returns></returns> public string PostJsonData(string data, string uri, string strAgent) { //先根据用户请求的uri构造请求地址 string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri); //创建Web访问对象 HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl); byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); //数据转成“UTF-8”的字节流 //设置参数的编码格式,解决中文乱码 myRequest.Method = "POST"; myRequest.ContentLength = buf.Length; //设置myRequest的MIME类型及内容长度 if (strAgent != "") { myRequest.UserAgent = strAgent; } myRequest.ContentType = "application/json"; using (Stream stream = myRequest.GetRequestStream()) //发送请求 { stream.Write(buf, 0, buf.Length); stream.Close(); } using (WebResponse myResponse = (WebResponse)myRequest.GetResponse()) //获取接口返回值 通过Web访问对象获取响应内容 { using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 { //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题 string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); return returnXml; } } } /// <summary> /// json格式执行Post方法 /// </summary> /// <param name="data"></param> /// <param name="uri"></param> /// <param name="strtoken"></param> /// <returns></returns> public string PostJsonWithAuth(string data, string uri, string strtoken) { string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri); HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl); myRequest.Method = "POST"; myRequest.Headers.Add("Authorization", strtoken); byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); myRequest.ContentLength = buf.Length; myRequest.ContentType = "application/json"; myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; //发送请求 using (Stream stream = myRequest.GetRequestStream()) { stream.Write(buf, 0, buf.Length); stream.Close(); } using (WebResponse myResponse = (WebResponse)myRequest.GetResponse()) //获取接口返回值 通过Web访问对象获取响应内容 { using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 { //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题 string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); return returnXml; } } } /// <summary> /// form-data格式执行Post方法 传图片 /// </summary> /// <param name="url"></param> /// <param name="imageInfo"></param> /// <param name="stringDict"></param> /// <param name="strAuth_token"></param> /// <returns></returns> public string PostFormData(string url, Dictionary<string, string> imageInfo, System.Collections.Specialized.NameValueCollection stringDict, string strAuth_token) { string responseContent = ""; try { string serviceUrl = string.Format("{0}/{1}", this.BaseUri, url); var webRequest = (HttpWebRequest)WebRequest.Create(serviceUrl); webRequest.Headers.Add("Authorization", strAuth_token); var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); // 边界符 // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = 10000; //默认超时时间为10秒 webRequest.ContentType = "multipart/form-data; boundary=" + boundary; var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 开始边界符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 最后的结束符 var memStream = new MemoryStream(); //为系统内存提供流式的读写操作 memStream.Write(beginBoundary, 0, beginBoundary.Length); FileStream fileStream = null; #region 写入文件 if (imageInfo != null) { foreach (var item in imageInfo) { fileStream = null; fileStream = new FileStream(item.Value, FileMode.Open, FileAccess.Read); const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, item.Key, item.Value); var headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); var buffer = new byte[1024]; int bytesRead; // =0 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } } } #endregion var contentLine = Encoding.ASCII.GetBytes("\r\n"); memStream.Write(contentLine, 0, contentLine.Length); // 写入字符串的Key var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; if (stringDict != null) { foreach (byte[] formitembytes in from string key in stringDict.Keys select string.Format(stringKeyHeader, key, stringDict[key]) into formitem select Encoding.UTF8.GetBytes(formitem)) { memStream.Write(formitembytes, 0, formitembytes.Length); } } // 写入最后的结束边界符 memStream.Write(endBoundary, 0, endBoundary.Length); webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); using (var httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { responseContent = httpStreamReader.ReadToEnd(); } if (fileStream != null) { fileStream.Close(); } httpWebResponse.Close(); webRequest.Abort(); } } catch (Exception ex) { responseContent = ex.ToString(); } return responseContent; } #endregion #region Put请求 public string PutWithToken(string uri, string info, string strToken) { string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri); HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl); //后台或可使用WebRequest request = WebRequest.Create(url); myRequest.Headers.Add("Authorization", strToken); //数据转成“UTF-8”的字节流 //设置参数的编码格式,解决中文乱码 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(info); myRequest.Method = "Put"; myRequest.ContentLength = buf.Length; myRequest.ContentType = "application/json"; //myRequest.MaximumAutomaticRedirections = 1; //myRequest.AllowAutoRedirect = true; //发送请求 using (Stream stream = myRequest.GetRequestStream()) { stream.Write(buf, 0, buf.Length); stream.Close(); } using (WebResponse myResponse = (WebResponse)myRequest.GetResponse()) //获取接口返回值 通过Web访问对象获取响应内容 { using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 { //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题 string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); return returnXml; } } } #endregion #region Delete请求 public string Delete(string data, string uri, string strServerToken) { string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri); HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl); myRequest.Headers.Add("Authorization", strServerToken); myRequest.Method = "DELETE"; myRequest.ContentType = "application/x-www-form-urlencoded"; //myRequest.MaximumAutomaticRedirections = 1; //myRequest.AllowAutoRedirect = true; if (data != "") { byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); myRequest.ContentLength = buf.Length; using (Stream stream = myRequest.GetRequestStream()) //发送请求 { stream.Write(buf, 0, buf.Length); stream.Close(); } } using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) //获取接口返回值 通过Web访问对象获取响应内容 { using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 { //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题 string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); return returnXml; } } } #endregion }
当前位置:
首页 > temp > 简明python教程 >
-
WebAPI :Get、Post、Delete、Put
记录和分享用过的技术、基础、方法
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
SQL Server -- 解决存储过程传入参数作为s
关于JS定时器的整理
JS中使用Promise.all控制所有的异步请求都完
js中字符串的方法
import-local执行流程与node模块路径解析流程
检测数据类型的四种方法
js中数组的方法,32种方法
前端操作方法
数据类型
window.localStorage.setItem 和 localStorage.setIte
如何完美解决前端数字计算精度丢失与数