1、加载Newtonsoft.Json
2、封装一个isbn查询接口类(接口来源于网络)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using System.Xml;
using System.IO;
using Google.Protobuf.WellKnownTypes;
using MySqlX.XDevAPI;
using System.Security.Policy;
namespace Book
{
internal class Isbn
{
public static async Task<String> GetBookByISBN(string isbn)
{
//https://data.isbn.work/openApi/getInfoByIsbn?isbn=9877302498407&appKey=ae1718d4587744b0b79f940fbef69e77
string doubanurl = "https://data.isbn.work/openApi/getInfoByIsbn?isbn=";
string key = "&appKey=ae1718d4587744b0b79f940fbef69e77";
string geturl = doubanurl + isbn + key;
HttpResponseMessage response;
try
{
HttpClient httpClient = new HttpClient();
response = await httpClient.GetAsync(geturl);//发送GET请求到该URL。
response.EnsureSuccessStatusCode();//使用`EnsureSuccessStatusCode`方法确保响应状态码表示成功。
}
catch(HttpRequestException ex)
{
MessageBox.Show("请求错误"+ex);
throw ex;
}
return await response.Content.ReadAsStringAsync();//* 使用`ReadAsStringAsync`方法将响应内容读取为字符串,并返回该字符串。
}
}
}
3、引入using System.Text.Json.Nodes;
4、解析isbn接口查询的数据,并将数据显示在控件上
private async void textBox6_TextChanged(object sender, EventArgs e)
{
string text = textBox6.Text;
textBox5.Text = textBox6.Text;
if (text.Length > 10)
{
string book = await Isbn.GetBookByISBN(text);
JObject jobject = JObject.Parse(book);
if (Convert.ToInt32(jobject["code"]) != 0)
{
MessageBox.Show(jobject["msg"].ToString());
}
else
{
JToken box = jobject["data"];
textBox2.Text = box["bookName"].ToString();
textBox3.Text = box["author"].ToString();
textBox4.Text = box["press"].ToString();
textBox5.Text = box["isbn"].ToString();
}
}
}
最终效果如下
注:接口可返回的数据,这些数据都可以解析调用