思路:
1.根据第三方接口返回的字段来创建实体类,用来接收数据
2.建立连接,提供两种方式。来获取数据
3.实体类转换并存储
方法一:URL 建立连接进行接收数据
依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.80</version> </dependency>
首先模拟一个接口,返回数据
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; /** * <p> * 前端控制器 * </p> * * @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<Jiushui> doHttp(){ List<Jiushui> list = jiushuiService.list(); return list; } /** 获取接口并保存到数据库的方法 */ @GetMapping("/saveMysql") public String saveMysql(){ savehttpService.saveMysql(); return "存入成功"; } }
接收数据对应的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; /** * <p> * * </p> * * @author zsp * @since 2022-04-25 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class Savehttp extends Model<Savehttp> 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; /** * <p> * 服务类 * </p> * * @author zsp * @since 2022-04-25 */ public interface SavehttpService extends IService<Savehttp> { 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; /** * <p> * 服务实现类 * </p> * * @author zsp * @since 2022-04-25 */ @Service public class SavehttpServiceImpl extends ServiceImpl<SavehttpMapper, Savehttp> 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<Savehttp> list = JSONArray.parseArray(result.toJSONString(), Savehttp.class);
savehttpMapper.saveBatch(list);
postman测试,成功。(在测试类测的时候需要将项目启动,不然报错。)
方法二:httpClient建立连接获取数据
package com.zsp.quartz.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.zsp.quartz.entity.User; import com.zsp.quartz.entity.param.*; 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.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.io.IOException; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/test") @CrossOrigin public class TestController { @PostMapping("/list") public List<User> lists() { User u1 = User.builder().id(1L).name("张三").build(); User u2 = User.builder().id(2L).name("李四").build(); List<User> userList = new ArrayList<>(); userList.add(u1); userList.add(u2); return userList; } @PostMapping("callInterFace") public void callInterFace() { String path = "http://localhost:8088/test/list"; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建post请求 HttpPost httpPost = new HttpPost(path); httpPost.setHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdoYW8iLCJpZCI6IjE5IiwiZXhwIjoxNjk1NjE0OTgxfQ.rDwH10MvXToi5aeCxabvNR3M9sIeE9xDD0QNaj5ynBw"); CloseableHttpResponse response = null; try { // 由客户端执行(发送)post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { List<User> list = JSONArray.parseArray(EntityUtils.toString(responseEntity), User.class); System.out.println(list); } } catch (ParseException | IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
仅作记录。觉得有用点个赞吧。
2023/10/08更新
为了更直观,只在controller层做了演示。
package com.zsp.quartz.controller; import com.alibaba.fastjson.JSONArray; import com.zsp.quartz.entity.User; import com.zsp.quartz.entity.param.*; import org.apache.http.HttpEntity; import org.apache.http.ParseException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.io.IOException; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/test") @CrossOrigin public class TestController { @PostMapping("/test") @Validated public String login(@RequestBody @Valid DeleteByIdParam param) { return "你好啊,doPost方法" + param.getId(); } @PostMapping("/list") public List<User> lists() { User u1 = User.builder().id(1L).name("张三").build(); User u2 = User.builder().id(2L).name("李四").build(); List<User> userList = new ArrayList<>(); userList.add(u1); userList.add(u2); return userList; } @PostMapping("callInterFace") public void callInterFace() { String path = "http://localhost:8088/test/list"; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建post请求 HttpPost httpPost = new HttpPost(path); httpPost.setHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdoYW8iLCJpZCI6IjE5IiwiZXhwIjoxNjk1NjE0OTgxfQ.rDwH10MvXToi5aeCxabvNR3M9sIeE9xDD0QNaj5ynBw"); CloseableHttpResponse response = null; try { // 由客户端执行(发送)post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { List<User> list = JSONArray.parseArray(EntityUtils.toString(responseEntity), User.class); System.out.println(list); } } catch (ParseException | IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
学习作为记录,大家一起进步
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_55627541/article/details/124431771
标签:Java,http,接口,zsp,获取数据,import,apache,org,com From: https://www.cnblogs.com/isme-zjh/p/18134364