准备:安装了.NET开发和Nuget的VS,新建一个NetFramework4.0以上的Winform程序
方案一(直接调用api,适合新手练习)
界面设计
代码
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string HttpGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//创建HttpWebRequest实例并建立请求
request.Method = "GET";//设定请求方法为“GET”
request.Accept = "text/html, application/xhtml+xml, */*";//“设定接受数据类型”
request.ContentType = "application/json";//会话类型
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//接受数据
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
private void Form1_Load(object sender, EventArgs e)
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;//设定TSL协议,防止出错
string a = HttpGet("https://v.api.aa1.cn/api/api-wenan-mingrenmingyan/index.php?aa1=text");
int length = a.Length;
int start = 3;
string txt = a.Substring(start, length - 7);//去除文本中的<p>
label1.Text = txt;
}
}
}
效果
方案二(调用打包好的api,只需要手写一行代码,适合实际生产)
1.界面同方案一
2.这一步很重要,单击【项目】菜单里的【管理Nuget程序包】,然后搜索“Sayingmaker”,找到并单击第一个搜索结果,再单击安装(如图)
3.代码
using System;
using System.Windows.Forms;
namespace DLLtest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label.Text = SayingMaker.Maker.GetSaying();//这是唯一需要手写的,其余的vs会自动生成
}
}
}
4.效果同上