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

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());
        }
    }
}

执行结果:
代码执行结果

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

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值