快速使用:调用第三方接口获取数据(简易版)_myme95的博客-CSDN博客_调用第三方接口
controller层
private String jokeApiKey = "40ff81dexxxxxxxxxxxx97a39d39";@AutowiredApiService apiService;/*** 京东万象-笑话api*/@GetMapping("/getJoke")@ResponseBodypublic Output jokeApi() throws Exception {//得到long类型当前时间long l = System.currentTimeMillis();//new日期对象Date date = new Date(l);//转换提日期输出格式SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");String time = dateFormat.format(date);String api = "https://way.jd.com/showapi/wbxh?time=" + time + "&page=1&maxResult=20&showapi_sign=bd0592992b4d4050bfc927fe7a4db9f3&appkey=" + jokeApiKey;String str = apiService.httpRequest(api);JSONObject jsonObject = JSON.parseObject(str);String code = jsonObject.getString("code");if (code == null) {throw new Exception("数据获取有误!");}JSONObject resultJsonObject = jsonObject.getJSONObject("result");JSONObject bodyJsonObject = resultJsonObject.getJSONObject("showapi_res_body");JSONArray contentListArray = bodyJsonObject.getJSONArray("contentlist");List<Item> itemList = JSONArray.parseArray(contentListArray.toJSONString(),Item.class);Output output = new Output();output.setResult(itemList);return output;}
service层
在controller层里我说了,我们暂时只需要关注1~4步。
你在controller层里面拼接好了地址以后,就可以把拼接了你appKey、time等等参数的url传给service进行进一步的业务处理,也就是我们真正的调用三方接口的处理逻辑。
public String httpRequest(String apiPath) {BufferedReader in = null;StringBuffer result = null;//调用的api的接口地址String apiUrl = apiPath;try {URL url = new URL(apiPath);//打开和url之间的连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");connection.setRequestProperty("Charset", "utf-8");connection.connect();result = new StringBuffer();//读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result.append(line);}return result.toString(); //返回json字符串} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (in != null) {in.close();}} catch (IOException e) {e.printStackTrace();}}return null;}
这个方法执行成功之后,返回的是一个json字符串。
将获取的数据转换为Json对象。
拿到了返回数据之后,你就可以把值一个一个取出来然后存到你的数据库里。当然你的数据库里一定要先有一张对应的表才是。
json包我用的是fastjson,它的maven依赖如下。
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.57</version></dependency>
输出类Output的代码(可以根据个人需求做个性化定制~,比如你可以多返回一个errorcode什么的,这都是Ok的):
import java.io.Serializable;public class Output implements Serializable {//serialVersionUID 这个是序列化时要用到的,idea可以自动生成,//但是我也不知道怎么生成,可以自己百度一下。这是公司大佬之前//封装的(此处感恩大佬又让我学到了新东西!)private static final long serialVersionUID = 7247613666080613254L;//状态码,比如这里定义status默认200,代表接口调用成功。代表网络上的成功而已。private int status = 200; //code有的人会写成errorCode,是“错误代码”的意思。这是代表业务逻辑上的成功与否‘//默认0,代表你的业务逻辑没问题,此次调用成功了。打个比方,你调用接口进行一个“新增”操作,//新增成功返回一个code=0代表你此次新增成功了。否则你返回一个code=201(或者其他随便什么//只要你喜欢)代表新增失败。private int code = 0; //错误信息,比如“新增失败!”等private String message;//如果新增成功,就把你想要抛出去的东西放在result里面跑出去。result用Object定义。随便你//放什么进去都OK ,String、int、List... whatever you wantprivate Object result;public int getStatus() {return this.status;}public void setStatus(int status) {this.status = status;}public int getCode() {return this.code;}public void setCode(int code) {this.code = code;}public String getMessage() {return this.message;}public void setMessage(String message) {this.message = message;}public Object getResult() {return this.result;}public void setResult(Object result) {this.result = result;}public Output() {}public Output(Object result) {this.result = result;}public Output(int code, String message) {this.code = code;this.message = message;}}
后续问题
今天遇到一个小问题。我调用一个api,那个api的数据提交是form表单。而我之前包括这篇文章写的方法都是以json格式传参数的。所以就出现了问题,当我以json格式的参数去请求一个本应以表单形式提交参数的api,那边防火墙会拦截下来,告诉我参数不合法。
后来我知道了,post方法的参数请求有两种形式:form表单形式(key=value数据格式)和json形式(key:value数据形式)。这两种方式对应的调用方法大同小异。