12-请求响应-分层解耦

主要学习以下几个部分:请求、响应和分层解耦(这里主要介绍分层解耦部分)

 

数据网址:console-mock.apipost.cn/mock/4250f8d4-b605-47eb-9777-07e29548dbb8/list

案例:通过上述数据网址,获取其中的name,image,gender,job数据,将其作为Emp类返回

这里需要注意,将获取的数据转为对象,获取其中的data数据过程中,需要用到fastjson依赖

1)不使用分层解耦

Emp.java

package com.malingshu.entity;

public class Emp {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    private String name;
    private String image;
    private String gender;
    private String job;
}

EmpController.java

package com.malingshu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malingshu.entity.Emp;
import com.malingshu.entity.Result;
import com.malingshu.service.IEmpService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@RestController
public class EmpController {

    private final IEmpService empService;

    public EmpController(IEmpService empService) {
        this.empService = empService;
    }

    // 不使用分层解耦
    @RequestMapping("/getData")
    public Result getData() {
        List<Emp> list = new ArrayList<>();

        // 1.接口地址
        String URL_ADDRESS = "https://console-mock.apipost.cn/mock/4250f8d4-b605-47eb-9777-07e29548dbb8/list";

        // 2.通过GET请求获取数据
        String result = "";
        try {
            // 传入参数
            String realUrl = URL_ADDRESS;
            System.out.println(realUrl);
            URL resultUrl = new URL(realUrl);
            HttpURLConnection conn = (HttpURLConnection) resultUrl.openConnection();
            // 在连接之前设置属性

            // Content-Type实体头用于向接收方指示实体的介质类型,指定HEAD方法送到接收方的实体介质类型,或GET方法发送的请求介质类型
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 设置打开与此URLConnection引用的资源的通信链接时使用的指定超时值(以毫秒为单位)
            conn.setConnectTimeout(10000);
            // 将读取超时设置为指定的超时时间,以毫秒为单位。
            // conn.setReadTimeout(60000);
            conn.setRequestMethod("GET");
            // Post 请求不能使用缓存
            conn.setUseCaches(false);

            // 建立连接
            conn.connect();
            // 获取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null) {
                result += line;
            }
            reader.close();
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 3.将获取的数据转为对象,获取其中的data数据
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray jsonArray = jsonObject.getJSONArray("data");

        // 4.遍历jsonArray数据, 添加到list中
        for(int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            Emp emp = new Emp();
            emp.setName(object.getString("name"));
            emp.setImage(object.getString("image"));
            emp.setGender(object.getString("gender"));
            emp.setJob(object.getString("job"));
            list.add(emp);
        }

        return Result.success(list);
    }
}

 

2)使用分层解耦

这里将EmpController.java 拆分为:IEmpService接口类和EmpServiceImpl实现类

EmpController.java

package com.malingshu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malingshu.entity.Emp;
import com.malingshu.entity.Result;
import com.malingshu.service.IEmpService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@RestController
public class EmpController {

    private final IEmpService empService;

    public EmpController(IEmpService empService) {
        this.empService = empService;
    }

    // 使用三层解耦
    @RequestMapping("/getData2")
    public Result getData2() {
        return Result.success(empService.getData2());
    }
}

IEmpService.java

package com.malingshu.service;

import com.malingshu.entity.Emp;

import java.util.List;

public interface IEmpService {
    public List<Emp> getData2();
}

EmpServiceImpl.java(代码的实现,主要是在这个部分)

package com.malingshu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malingshu.service.IEmpService;
import com.malingshu.entity.Emp;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Service
public class EmpServiceImpl implements IEmpService {

    @Override
    public List<Emp> getData2() {
        // 获取员工列表数据
        List<Emp> list = new ArrayList<>();

        // 1.接口地址
        String URL_ADDRESS = "https://console-mock.apipost.cn/mock/4250f8d4-b605-47eb-9777-07e29548dbb8/list";

        // 2.通过GET请求获取数据
        String result = Get(URL_ADDRESS);

        // 3.将获取的数据转为对象,获取其中的data数据
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray jsonArray = jsonObject.getJSONArray("data");

        // 4.遍历jsonArray数据, 添加到list中
        for(int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            Emp emp = new Emp();
            emp.setName(object.getString("name"));
            emp.setImage(object.getString("image"));
            emp.setGender(object.getString("gender"));
            emp.setJob(object.getString("job"));
            list.add(emp);
        }

        return list;
    }

    public String Get(String url){
        try {
            // 传入参数
            String realUrl = url;
            System.out.println(realUrl);
            URL resultUrl = new URL(realUrl);
            HttpURLConnection conn = (HttpURLConnection) resultUrl.openConnection();
            // 在连接之前设置属性

            // Content-Type实体头用于向接收方指示实体的介质类型,指定HEAD方法送到接收方的实体介质类型,或GET方法发送的请求介质类型
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 设置打开与此URLConnection引用的资源的通信链接时使用的指定超时值(以毫秒为单位)
            conn.setConnectTimeout(10000);
            // 将读取超时设置为指定的超时时间,以毫秒为单位。
            // conn.setReadTimeout(60000);
            conn.setRequestMethod("GET");
            // Post 请求不能使用缓存
            conn.setUseCaches(false);

            // 建立连接
            conn.connect();
            // 获取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String result = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            reader.close();
            conn.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("获取实时数据失败");
        return null;
    }

}

 

 

 

 

posted @ 2024-04-14 17:11  马铃薯1  阅读(2)  评论(0编辑  收藏  举报