Winform C#客户端调用接口方法封装
编码中,偶尔需要调用其他方提供的API或者其他端交互的API。封装了常用的调用的get请求与post的请求。
接口返回值为Json,复制返回值通过VisualStudio 【编辑】--》【选择性粘贴】--》【将Json粘贴为类】可以自动生成返回结果类,类型可以修改为有意义的,但是字段属性不能修改,要与接口返回一致。通过json序列化,将结果序列化为可用的对象。
需要引用:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Specialized;
namespace SmartDP.Common.Utils
{
public class CallInterfaceDemo
{
/// <summary>
/// Get 请求 返回Json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="dicParams"></param>
/// <returns></returns>
public T GetInterfaceDemo<T>(string url, Dictionary<string,string> dicParams)
{
T t1 = default(T);
StringBuilder sbUrl = new StringBuilder();
string result = "";
try
{
//拼接访问地址
sbUrl.Append(url);
//拼接get接口的参数
int i = 0;
foreach (var key in dicParams.Keys)
{
if (i == 0)
{
sbUrl.Append("?" + key+"=").Append(dicParams[key]);
}
else
{
sbUrl.Append("&" + key + "=").Append(dicParams[key]);
}
i++;
}
//网络接口请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sbUrl.ToString());
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
t1 = JsonConvert.DeserializeObject<T>(result);
return t1;
}
catch (Exception ex)
{
return t1;
}
}
/// <summary>
/// 调用post的接口 ContentType='multipart/form-data'
/// </summary>
/// <param name="url"></param>
/// <param name="dicParams"></param>
/// <param name="filepaths"></param>
/// <returns></returns>
public string PostDemo(string url, Dictionary<string, string> dicParams, List<string> filepaths)
{
string postUrl = url;
try
{
// 拼接同文件一同上传的表单文本域及值(即传入的参数)
NameValueCollection nvc = new NameValueCollection();
foreach (var key in dicParams.Keys)
{
nvc.Add(key, dicParams[key]);
}
StringBuilder sb = new StringBuilder();
string boundary = "----------------" + DateTime.Now.Ticks.ToString("x"); // 边界符
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); // 由于HttpWebRequest没有提供属性来方便传参,所以下面我们只能自己模拟传参
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; // 声明数据类型
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; // key就是{0},value是{1}
foreach (string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
sb.Append(formitem);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
// 这里key是{0},value是{1}
string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
// 逐个将文件内容写入流
for (int i = 0; i < filepaths.Count; i++)
{
FileInfo fi = new FileInfo(filepaths[i]);
// 写入文件开始标记
string header = string.Format(headerTemplate, "file", fi.Name);
sb.Append(header);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024 * 8];//每次上传8M
int bytesRead = 0;
// 写入文件内容
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
sb.Append("\r\n--" + boundary + "--\r\n");
// 将结束标记写入内存流
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
memStream.Write(boundarybytes, 0, boundarybytes.Length);
httpWebRequest.ContentLength = memStream.Length;//流总大小
Stream requestStream = httpWebRequest.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string ret = reader.ReadToEnd();
return ret;
}
catch (Exception ex)
{
return "{\"result\":\"99\",\"message\":\"调用外部接口发生异常(" + ex.Message + ")\",\"data\":null}";
}
}
}
}
本文介绍如何在Winform应用中封装C#的GET和POST接口调用方法,用于调用外部API。利用Visual Studio的工具将JSON转换为类,并确保序列化和反序列化的正确性,以实现与接口的顺利交互。

1万+

被折叠的 条评论
为什么被折叠?



