简介
为了便于C#访问远程WebApi,特定义此函数。
- 函数签名:
string InvokeWebApiPost(string url, string param, int timeout = 3000)
- 参数列表:
url
需要访问的连接,如http://106.12.6.198:8080/register/QDasApi
param
参数列表,如api=info&imei=864768013300113&arg=20190419
timeout
超时时间,单位毫秒,默认为3秒。
- 返回类型:结果字符串。
示例
以下是显示本机信息,并利用接口,发现到远程主机的代码。
注:可直接访问以下相同地址测试api
http://106.12.6.198:8080/register/QDasApi?api=info&imei=864768013300113&arg1=Test
// 使用自定义的类获得的系统信息,如无此类,可以直接将info赋值
string info = WindGoes6.Sys.ConsoleInvoker.RunDosCommand("systeminfo");
info = info.Replace("\r", "").Replace("\n", "<br>");
info = Convert.ToBase64String(Encoding.UTF8.GetBytes(info)).Replace("+", "-").Replace("/", "_");
string url = $"http://106.12.6.198:8080/register/QDasApi";
string convertid = "T201904";
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string verstion = "alpha1";
string param = $"api=sysinfo&key={convertid}_{verstion}_{datetime}&arg1={info}";
string pagehtml = WindGoes6.Web.WebApiInvoker.InvokeWebApiPost(url, param);
string outhtml = "C:\\data\\test.html";
File.WriteAllText(outhtml, pagehtml, Encoding.Default);
Process.Start(outhtml);
一些测试结论
- post默认最大长度为2M
- 参数个数几百个是OK的,貌似没有限制。
- 单个长度测试是4096(应该可以修改)
源代码
/// <summary>
/// 调用指定的url以post方式调用,默认超时时间为3000毫秒。
/// </summary>
/// <param name="url">待调用链接。</param>
/// <param name="param">参数列表,格式如 api=value1&arg1=value2</param>
/// <param name="timeout">超时时间(单位毫秒),默认值为3000。</param>
/// <returns>执行结果。</returns>
public static string InvokeWebApiPost(string url, string param, int timeout = 3000)
{
// 将参数字节化
byte[] postdatabyte = Encoding.UTF8.GetBytes(param);
// 配置读写函数
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = timeout;
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0";
request.ContentLength = postdatabyte.Length;
request.AllowAutoRedirect = false;
request.KeepAlive = false;
// 调用函数
using (Stream stream = request.GetRequestStream())
stream.Write(postdatabyte, 0, postdatabyte.Length);
// 获取返回值。
string returned = null;
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
returned = streamReader.ReadToEnd();
}
return returned;
}