应用场景
应用程序编程接口(Application Programming Interface,简称:API),是服务方定制开发一些预先定义的函数方法,并提供访问的方式及规则。访问 API 的开发人员无需理解其内部工作机制,只根据服务方提供的说明及规则,提交参数数据,并获取有需要的处理结果。
Web API 是 Web 服务器和 Web 浏览器之间的应用程序处理接口。我们常见的模式是访问 Web API Url 地址,POST 或 GET 所需要的参数数据,并获取 Json 、XML或其它指定格式的处理结果。
范例运行环境
操作系统: Windows Server 2019 DataCenter
.net版本: .netFramework4.0 或以上
开发工具:VS2019 C#
WebService 类
设计
WebService 类的 GetResponseResult 方法提供了访问 Web API Url 的能力,方法返回字符串(即API返回的处理结果),另外WebService 类还提供了 ErrorMessage 属性,通过访问此属性是否为空以判断方法是否正确返回了处理结果,GetResponseResult方法的 使用说明见如下表格:
序号 | 参数名 | 类型 | 说明 |
---|---|---|---|
1 | url | string | 要访问的URL地址 |
2 | encoding | System.Text.Encoding | 字符编码格式 |
3 | method | string | 提交的方法类型,如 "POST","GET" |
4 | postData | string | 提交的数据包 |
5 | headers | string[] | 传递请求头的字符串数组,如: string[] headers = new string[] {"key1:value1","key2:value2" }; 其中每一项的关键名和关键值用冒号分隔 |
6 | ContentType | string | 内容类型,默认为 ContentType= "application/x-www-form-urlencoded" |
实现
实现代码如下:
public sealed class WebService { public string ErrorMessage = ""; public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData) { return GetResponseResult(url,encoding,method,postData,null); } public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData,string[] headers,string ContentType= "application/x-www-form-urlencoded") { method = method.ToUpper(); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; if (method == "GET") { try { WebRequest request2 = WebRequest.Create(@url); request2.Method = method; WebResponse response2 = request2.GetResponse(); Stream stream = response2.GetResponseStream(); StreamReader reader = new StreamReader(stream, encoding); string content = reader.ReadToEnd(); return content; } catch (Exception ex) { ErrorMessage = ex.Message; return ""; } } Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.Timeout = 1000000; if (headers != null) { for(int i = 0; i < headers.GetLength(0); i++) { if (headers[i].Split(':').Length <2) { continue; } if (headers[i].Split(':').Length > 1) { if (headers[i].Split(':')[0] == "Host") { request.Host = headers[i].Split(':')[1]; continue; }else if (headers[i].Split(':')[0] == "Content-Type") { request.ContentType = headers[i].Split(':')[1]; continue; } } request.Headers.Add(headers[i]); } } request.ContentType = ContentType; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); string content = sr.ReadToEnd(); sr.Close(); sr.Dispose(); return content; } catch (Exception ex) { ErrorMessage = ex.Message; return ""; } }//get response result }
调用
调用示例代码如下:
string content = "{\"key1\": 1,\"key2\": \"value2\"}"; string apiUrl = "https://api.t.com/test.aspx"; WebService ws = new WebService(); string resultStr = ws.GetResponseResult(settingUrl, Encoding.UTF8, "POST", content); if(ErrorMessage!=""){ Response.Write("访问没有成功,错误信息:"+ErrorMessage); }else{ Response.Write(resultStr); }
其它
我们在 WebService 类里创建了另一个实用方法:DownLoadFile,即提供对应的下载地址可以指定下载到本地文件,方法返回字符串(为空表示下载成功,不为空则显示错误信息)方法的使用说明见如下表格:
序号 | 参数名 | 类型 | 说明 |
---|---|---|---|
1 | url | string | 要下载的URL地址 |
2 | localfile | string | 要保存的本地完整路径地址 |
实现代码如下:
public string DownLoadFile(string url, string localfile) { string pathUrl = url; System.Net.HttpWebRequest request = null; System.Net.HttpWebResponse response = null; //请求网络路径地址 request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl); request.Timeout = 5000; // 超时时间 //获得请求结果 try { response = (System.Net.HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); //先创建文件 Stream sos = new System.IO.FileStream(localfile, System.IO.FileMode.Create); byte[] img = new byte[1024]; int total = stream.Read(img, 0, img.Length); while (total > 0) { //之后再输出内容 sos.Write(img, 0, total); total = stream.Read(img, 0, img.Length); } stream.Close(); stream.Dispose(); sos.Close(); sos.Dispose(); return ""; } catch (Exception e) { return e.Message; } }