java调用别人的接口获取数据存到mysql数据库

1.根据接口返回的字段创建数据库表

2.创建对应这个表的controller,service,mapper,pojo

3.在controller层调用Impl实现类。具体业务:接收数据并保存在数据库, mapper层写插入sql

方法一:URL 建立连接进行接收数据

依赖


            org.apache.httpcomponents
            httpclient
        

        
            com.alibaba
            fastjson
            1.2.80
        

首先模拟一个接口,返回数据

controller层 用的mybatis-plus

package com.zsp.chaoshi.controller;


import com.zsp.chaoshi.pojo.Jiushui;
import com.zsp.chaoshi.service.JiushuiService;
import com.zsp.chaoshi.service.SavehttpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 

* 前端控制器 *

* * @author zsp * @since 2022-04-25 */ @CrossOrigin @RestController @RequestMapping("/savehttp") public class SavehttpController { @Autowired private JiushuiService jiushuiService; @Autowired private SavehttpService savehttpService; /** 模拟对外暴露的接口 */ @GetMapping("/doGetControllerOne") public List doHttp(){ List list = jiushuiService.list(); return list; } /** 获取接口并保存到数据库的方法 */ @GetMapping("/saveMysql") public String saveMysql(){ savehttpService.saveMysql(); return "存入成功"; } }

要接收controller层的doGetControllerOne传过来的数据,所以根据传过来的字段首先建立数据库,要跟传过来的数据的字段保持一致。继承extends Model是为了用里面的insert方法,也可以在mapper.xml里面自己写方法。

接收数据对应的pojo类。

package com.zsp.chaoshi.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * 

* *

* * @author zsp * @since 2022-04-25 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class Savehttp extends Model implements Serializable { private static final long serialVersionUID=1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; private String name; private Integer jiage; private String tupian; private Integer isdeleted; @TableField("VERSION") private Integer version; private int sex; }

service层

package com.zsp.chaoshi.service;

import com.zsp.chaoshi.pojo.Savehttp;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * 

* 服务类 *

* * @author zsp * @since 2022-04-25 */ public interface SavehttpService extends IService { void saveMysql(); }

serviceImpl类

package com.zsp.chaoshi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zsp.chaoshi.pojo.Savehttp;
import com.zsp.chaoshi.mapper.SavehttpMapper;
import com.zsp.chaoshi.service.SavehttpService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Optional;

/**
 * 

* 服务实现类 *

* * @author zsp * @since 2022-04-25 */ @Service public class SavehttpServiceImpl extends ServiceImpl implements SavehttpService { @Autowired SavehttpMapper savehttpMapper; @Override public void saveMysql() { String path = "http://127.0.0.1:8083/savehttp/doGetControllerOne"; BufferedReader in = null; StringBuffer result = null; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); result = new StringBuffer(); //读取url的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } //我接受的数据是[{}]数组类型的,所以要用数组类型的JSON去接收,如果接收的是Object{},那么就要用JSONObject去接收 //JSONArray array = JSONArray.parseArray(str); 接收的是数组格式的数据 //JSONObject obj = JSONArray.parseObject(str);接收的是对象 //parseArray方法接收的是String字符串,所以不能直接传Stringbuffer进来,要进行valueOf转换 //这里用valueOf是因为如果对象为空,则返回null字符串;否则用toString的话,对象为空则会报空指针异常 JSONArray jsonArray = JSON.parseArray(String.valueOf(result)); //此时存进来的jsonArray就是JSON数组 //[ // { // "tupian":"100", // "isDeleted":0, // "jiage":120, // "sex":1, // "name":"外星人笔记本", // "id":1, // "version":2 // }, // { // "tupian":"20", // "isDeleted":0, // "jiage":666, // "sex":2, // "name":"11111", // "id":52, // "version":0, // } //] //接下来就是遍历数组下标,获取每个下标里面的数据 也就是取值 //用法: // for(int i =0; i <= array.size(); i++){ // array[i].get(key); // } for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); //获取 Savehttp savehttp = new Savehttp(); //savehttp.setId(jsonObject.getInteger("id")); savehttp.setName(jsonObject.getString("name")); savehttp.setJiage(jsonObject.getInteger("jiage")); savehttp.setTupian(jsonObject.getString("tupian")); savehttp.setIsdeleted(jsonObject.getInteger("isDeleted")); savehttp.setVersion(jsonObject.getInteger("version")); savehttp.setSex(jsonObject.getInteger("sex")); savehttp.insert(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } }

在数据转换时还有一种更简洁的方法:需要用到fastjson的依赖。
List list = JSONArray.parseArray(result.toJSONString(), Savehttp.class);

savehttpMapper.saveBatch(list);

postman测试,成功。(在测试类测的时候需要将项目启动,不然报错。)

方法二:httpClient建立连接获取数据

这个没有写接口,只在Test里面做了测试别的不变,有的import没用到。

 import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsp.chaoshi.mapper.JiushuiMapper;
import com.zsp.chaoshi.mapper.SavehttpMapper;
import com.zsp.chaoshi.mapper.UserMapper;
import com.zsp.chaoshi.pojo.Jiushui;
import com.zsp.chaoshi.pojo.Savehttp;
import com.zsp.chaoshi.pojo.User;
import com.zsp.chaoshi.service.JiushuiService;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
@Test
    public void doGetTestOne() {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8083/savehttp/doGetControllerOne");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                JSONArray jsonArray= JSON.parseArray(EntityUtils.toString(responseEntity));
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Savehttp savehttp = new Savehttp();
                   savehttp.setName(jsonObject.getString("name"));
                savehttp.setJiage(jsonObject.getInteger("jiage"));
                savehttp.setTupian(jsonObject.getString("tupian"));
                savehttp.setIsdeleted(jsonObject.getInteger("isDeleted"));
                savehttp.setVersion(jsonObject.getInteger("version"));
                savehttp.setSex(jsonObject.getInteger("sex"));
                savehttp.insert();
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

仅作记录。觉得有用点个赞吧。

你可能感兴趣的:(笔记,springboot,java,spring,intellij,idea)