当一个Api接口给到你,考虑该如何调用?

前言

本人对于接口的调用,也没有清晰的认识,还停留在浏览博客文章,然后东拼西凑代码块,勉强能够提取到接口部分有价值的内容。所以在这里理清脉络的同时,给初学者提供一点参考,不足之处,欢迎各位大佬指正、补充。

1. 接口来源

在github上,有一个叫public-api的项目(star:235k),里面有许多类型的接口,包括Animals(动物)、Anime(动漫)、Art&Design(艺术设计)等。有些需要认证(Auth:apiKey),在这里举例的是Inshorts News(说明链接:https://github.com/cyberboysumanjay/Inshorts-News-API),公开免费调用。

2. 接口文档

新闻种类有:
all、national //Indian News only、business、sports、world、politics、technology、startup、entertainment、miscellaneous、hatke、science、automobile
可以通过修改category,查询到自己感兴趣的新闻。案例接口如下:
https://inshorts.deta.dev/news?category={category_name}

3. 调用演示

使用category=‘sports’作为演示,由于数量较多(Array:25),编程中只取数组下标为1的。
①service层为InshortsNewsService
service层使用@service注解,其中,方法getNews需要传入String类型参数category,访问接口Api的url,读取到JSON格式的数组并返回下标为1的JSON数据。

@Service
public class InshortsNewsService{
    public JSONObject getNews(String category){
        String url="https://inshorts.deta.dev/news?category="+category;//拼接String类型接口链接
        StringBuilder sb=new StringBuilder();
        try {
            URL httpUrl=new URL(url);//将String转换为URL类型
            HttpURLConnection conn=(HttpURLConnection) httpUrl.openConnection();//URL开启连接并强制转换为HttpURLConnection类型
            conn.setRequestMethod("GET");//设置请求方式
            BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//以utf-8的编码方式从字节流到字符流
            String inputLine=null;
            while ((inputLine=in.readLine())!=null){
                sb.append(inputLine);//当输出流不为空时,拼接字符串
            }
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject json=JSONObject.parseObject(sb.toString());//字符串类型转换为JSON类型
        JSONArray jsonArray=json.getJSONArray("data");//key为data是JSONArray
        return jsonArray.getJSONObject(1);//返回JSON数组下标为1的数据
    }
}

②controller层为InshortsNewsController
controller层使用@RestController注解,是@Controller加上@RequestBody;
使用@Autowired注入InshortsNewsService对象;
使用@PostMapping指定访问路径;
JSON类型方法,接收传递参数@RequestParam(value=“category”)并调用service对象方法;

@RestController
public class InshortsNewsController {
    @Autowired
    InshortsNewsService inshortsNewsService;
    @PostMapping("test/getNews")
    public JSONObject getNews(@RequestParam(value="category") String category)throws Exception{
    JSONObject json=inshortsNewsService.getNews(category);
        return json;
    }
}

③html页面
引入jquery文件,在javascript中访问controller中的路径。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新闻</title>
    <script src="../bootstrap3/jquery-1.9.1.min.js"></script>//引入jquery
    <script src="../bootstrap3/js/bootstrap.js"></script>
</head>
<body>
<div>
<textarea id="yi"></textarea>//放新闻标题
    <br>
    <textarea id="er"></textarea>//放新闻作者
<br>
    <img id="san" src="#">//放新闻图片
</div>
</body>
<script type="text/javascript">
    var imgsrc
    //post方法访问controller层路径,传递参数,功能如下
    $.post('http://localhost:8080/test/getNews',{category:'sports'},function (res){
        var yi=document.getElementById("yi");//通过id获取对象(文本框)
        var er=document.getElementById("er");
        var author=res.author;//赋值变量为返回值中key=?
        var title=res.title;
        yi.value=title;//文本框填充内容
        er.value=author;
        imgsrc=res.imageUrl;
        $('#san').attr("src",imgsrc);//更换指定id标签中的属性值(src=?)
    })
</script>
</html>

4. 展望

到这里,咱们就简单取到Api接口中,类型为sports的新闻,并将下标为1的新闻标题、作者、配图通过html展示出来。在这里,category的类型是被我们写死的,希望之后就是能通过页面输入、提交,然后显示更多内容出来,让整个页面看起来更像是新闻网站。

附完整Array[1]:

{
"author":"Anmol Sharma",
"content":"The BCCI is reportedly unhappy with DC's gesture for Rishabh Pant in their match against LSG. DC hung Pant's jersey on roof of their dug-out. An IPL source told PTI that BCCI said the gesture seemed a \"bit over the top\". \"Such a gesture is reserved in case of ultimate tragedy/retirement. In this case...it was neither,\" the source said.",
"date":"05 Apr 2023,Wednesday",
"id":"d3df1ed3d7994f0192337914b5cb8f32",
"imageUrl":"https://static.inshorts.com/inshorts/images/v1/variants/jpg/m/2023/04_apr/5_wed/img_1680683940454_264.jpg?",
"readMoreUrl":"https://www.crictracker.com/cricket-news/ipl-2023-bcci-unhappy-with-delhi-capitals-jersey-gesture-for-rishabh-pant/?utm_campaign=fullarticle&utm_medium=referral&utm_source=inshorts ",
"time":"02:53 pm",
"title":"BCCI unhappy with DC's jersey gesture for Rishabh Pant: Reports",
"url":"https://www.inshorts.com/en/news/bcci-unhappy-with-dcs-jersey-gesture-for-rishabh-pant-reports-1680686587112"
}

完结撒花❀❀

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值