基于Restful接口的网络API接口调用方法

来源:互联网 发布:超级本 知乎 编辑:程序博客网 时间:2024/06/06 02:29

java原生方式调用API

1) 我们会使用fastjson解析json数据,会导入alibaba的fastjson依赖包:

<dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson</artifactId>    <version>1.2.40</version></dependency>

2) Demo源码:
以天行数据提供的一个API为例, 首先定义数据模型相关类:

NewsData类:

import java.util.List;public class NewsData {    private int error_code;    private String reason;    private List<News> result;    public int getError_code() {        return error_code;    }    public void setError_code(int error_code) {        this.error_code = error_code;    }    public String getReason() {        return reason;    }    public void setReason(String reason) {        this.reason = reason;    }    public List<News> getResult() {        return result;    }    public void setResult(List<News> result) {        this.result = result;    }}

News类:

public class News {    private String content;    private String hashId;    private long unixtime;    private String updatetime;    public String getContent() {        return content;    }    public void setContent(String content) {        this.content = content;    }    public String getHashId() {        return hashId;    }    public void setHashId(String hashId) {        this.hashId = hashId;    }    public long getUnixtime() {        return unixtime;    }    public void setUnixtime(long unixtime) {        this.unixtime = unixtime;    }    public String getUpdatetime() {        return updatetime;    }    public void setUpdatetime(String updatetime) {        this.updatetime = updatetime;    }}

测试类:

       //网络接口比如:http://api.tianapi.com/meinv/?key=网络提供的key&num=30&page=2        URL url = new URL("网络上面提供的API接口");import com.alibaba.fastjson.JSON;import java.io.InputStream;import java.net.URL;public class App {    public static void main(String[] args) throws  Exception {        //网络接口比如:http://api.avatardata.cn/Joke/QueryJokeByTime?key=网站提供的key&page=2&rows=10&sort=asc&time=1418775237        URL url = new URL("网络上面提供的API接口");        try (InputStream input = url.openStream()) {            StringBuilder jsonStr = new StringBuilder();            byte[] buffer = new byte[512];            int totalBytes;            while ((totalBytes = input.read(buffer)) != -1) {                jsonStr.append(new String(buffer, 0, totalBytes, "utf-8"));            }            //fastjson            NewsData newsData = JSON.parseObject(jsonStr.toString(), NewsData.class);            for (News model : newsData.getResult()) {                System.out.println("----------------");                System.out.println(model.getContent());            }        }    }}

运行结果:

HttpClient方式调用API

添加解析json数据依赖项,数据类还是DataNews和News类

测试类:

import com.fasterxml.jackson.databind.ObjectMapper;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class App2 {    public static void main(String[] args) throws  Exception {        HttpClient httpClient = HttpClients.createDefault();                //网络接口比如:http://api.avatardata.cn/Joke/QueryJokeByTime?key=网站提供的key&page=2&rows=10&sort=asc&time=1418775237        HttpGet getReq = new HttpGet("网络上面提供的API接口");        HttpResponse resp =httpClient.execute(getReq);        String jsonStr = EntityUtils.toString(resp.getEntity(),"utf-8");        System.out.println(jsonStr);        //jackson        ObjectMapper mapper = new ObjectMapper();        NewsData newsData = mapper.readValue(jsonStr,NewsData.class);        for(News news:newsData.getResult()){            System.out.println(news.getContent());            System.out.println("---------------------------");        }    }}

RestTemplate方式调用API

添加Spring-web和fastjson依赖项

 <dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.9.0</version></dependency><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-web</artifactId>    <version>4.3.11.RELEASE</version></dependency>

数据类还是DataNews和News类

测试类:

import org.springframework.web.client.RestTemplate;public class App3 {    public static void main(String[] args) throws Exception {        // Spring - RestTemplate        RestTemplate template = new RestTemplate();        NewsData newsData =                template.getForObject("http://api.avatardata.cn/Joke/QueryJokeByTime?key=0446a80169034e7fa28e9c58953c9c1a&page=2&rows=10&sort=asc&time=1418745237",                        NewsData.class);        for(News news:newsData.getResult()){            System.out.println(news.getContent());        }    }}

执行结果:
代码执行结果

如有问题,请及时指正,谢谢

原创粉丝点击