Spring boot 2.3.0 restful API commonly uses GET and POST requests to send unified return values

1) Introduction to RESTful
Definition: RESTful is a design style and development method of network applications. It is based on HTTP and can be defined in XML format or JSON format.

RESTful features:

1. Each URI is a unique resource identifier;

2. The client uses GET, POST, PUT and DELETE verbs to operate the server resources: GET is used to obtain resources, POST is used to create new resources (or update resources), PUT is used to update resources, and DELETE is used to DELETE resources;

3. The representation of resources is XML or HTML or JSON;

4. The interaction between client and server is stateless between requests;

2) Spring MVC support for RESTful
The functions are mainly realized through annotations, as follows:

@Controller: declares a controller that handles requests

@RequestMapping: requests to map addresses to corresponding methods. This annotation can be divided into the following types:

@GetMapping: get resources.

@PostMpping: create a new resource (or update it).

@PutMapping: updating resources, mainly used to update the entire resource.

@DeleteMapping: deletes a resource.

@PatchMapping: updating resources, mainly used to perform an operation and update some fields of resources.

@ResponsrBody: converts the response content to JSON format.

@RequestBody: convert the request content to JSON format.

@Restcontroller: equivalent to @ Controller+@ResponsrBody annotation.

3) RESTful API unified return value
Step 1: create an enumeration class to store the code and msg of business logic

package com.oysept.bean;
 
/**
 * Global unified return code and msg
 * @author ouyangjun
 */
public enum CodeEnum {
 
    RESULT_CODE_SUCCESS("S0000000", "SUCCESS"),
    RESULT_CODE_FAIL("F0000000", "FAIL"),
    ;
    
    private String code;
    private String msg;
    CodeEnum(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    
    public String getCode() {return code;}
    public void setCode(String code) {this.code = code;}
    
    public String getMsg() {return msg;}
    public void setMsg(String msg) {this.msg = msg;}
}

Step 2: create a unified return format, including status code, return message, return data and return time (self expandable)

package com.oysept.bean;
 
import java.io.Serializable;
import java.util.Date;
 
/**
 * Global return Result
 * @author ouyangjun
 */
public class Result<T> implements Serializable {
    
    private static final long serialVersionUID = 1L;
 
    private String code;
    private String msg;
    private T data;
    private Date time;
    
    public Result() {}
    public Result(CodeEnum codeenum, T data) {
        this.code = codeenum.getCode();
        this.msg = codeenum.getMsg();
        this.data = data;
        this.time = new Date();
    }
    
    public Result(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.time = new Date();
    }
    
    public String getCode() {return code;}
    public void setCode(String code) {this.code = code;}
    
    public String getMsg() {return msg;}
    public void setMsg(String msg) {this.msg = msg;}
    
    public T getData() {return data;}
    public void setData(T data) {this.data = data;}
    
    public Date getTime() {return time;}
    public void setTime(Date time) {this.time = time;}
}

Step 3: create an entity class for value transfer

package com.oysept.bean;
 
import java.io.Serializable;
 
public class ParamsVO implements Serializable {
    
    private static final long serialVersionUID = 1L;
 
    private String id;
    private String name;
    
    public String getId() {return id;}
    public void setId(String id) {this.id = id;}
    
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

4) RESTful GET pass participation return value
For the class introduced, the following GET and POST methods need to be used:

package com.oysept.controller;
 
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.oysept.bean.CodeEnum;
import com.oysept.bean.ParamsVO;
import com.oysept.bean.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class RestfulController {
    
    // GET or POST request code, as follows
}

The GET request can directly open the browser and directly enter the address for access.

The first: GET request without parameters

// Access address: http://localhost:8080/restful/get/noParamsGET
@RequestMapping(value="/restful/get/noParamsGET", method = RequestMethod.GET)
@ResponseBody
public Result<String> noParamsGET() {
    String data = "noParamsGET,No parameters GET request";
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

The second is a GET request with parameters, which obtains parameters through the HttpServletRequest.getParameter("") method

// Access address: http://localhost:8080/restful/get/httprequestGET?id=666&name=ouyangjun
@RequestMapping(value="/restful/get/httprequestGET", method = RequestMethod.GET)
@ResponseBody
public Result<String> httprequestGET(HttpServletRequest request, HttpServletResponse response) {
    // If the id is null, a null pointer error will be reported
    String id = request.getParameter("id");
    if (id == null || "".equals(id)) {
        return new Result<String>(CodeEnum.RESULT_CODE_FAIL, "id is null!");
    }
    String name = request.getParameter("name");
    String data = "requestGET, id: " + id + ", name: " + name;
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

The third type: GET request with parameters, pass values in the path, and the parameter names must be consistent

// Access address: http://localhost:8080/restful/get/oneParamsGET?id=666
@RequestMapping(value="/restful/get/oneParamsGET", method = RequestMethod.GET)
@ResponseBody
public Result<String> oneParamsGET(String id) {
    String data = "oneParamsGET, id: " + id;
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

The fourth type: GET request with parameters, multiple parameters pass values

// Access address: http://localhost:8080/restful/get/twoParamsGET?id=111&name=oysept
@RequestMapping(value="/restful/get/twoParamsGET", method = RequestMethod.GET)
@ResponseBody
public Result<String> twoParamsGET(String id, String name) {
    String data = "id: " + id + ", name: " + name;
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

Fifth: GET request, specify the name of the parameter, and then take the alias

// Access address: http://localhost:8080/restful/get/requestParamGET?id=111&name=oysept
@RequestMapping(value="/restful/get/requestParamGET", method = RequestMethod.GET)
@ResponseBody
public Result<String> requestParamGET(@RequestParam("id") String aaa, @RequestParam("name") String bbb) {
    String data = "aaa: " + aaa + ", bbb: " + bbb;
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

The sixth type: GET request, which transfers parameters as part of the path

// Access address: http://localhost:8080/restful/get/666/ouyangjun
@RequestMapping(value="/restful/get/{id}/{name}", method = RequestMethod.GET)
@ResponseBody
public Result<String> pathGET(@PathVariable("id") String aaa, @PathVariable("name") String bbb) {
    String data = "aaa: " + aaa + ", bbb: " + bbb;
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

The seventh method: GET method, form, and form transfer value

// Access address: http://localhost:8080/restful/get/noParamsObject
@RequestMapping(value="/restful/get/noParamsObject", method = RequestMethod.GET)
@ResponseBody
public Result<ParamsVO> noParamsObject() {
    ParamsVO vo = new ParamsVO();
    vo.setId("123");
    vo.setName("GOOD");
    return new Result<ParamsVO>(CodeEnum.RESULT_CODE_SUCCESS, vo);
}

5) RESTful POST transfer participation return value
POST requests cannot be accessed directly in the address bar. With the help of Postman tool, there are many http request software on the Internet.

The first type: POST no parameter request

// Access address: http://localhost:8080/restful/post/noParamsPost
@RequestMapping(value="/restful/post/noParamsPost", method = RequestMethod.POST)
@ResponseBody
public Result<String> noParamsPost() {
    String data = "noParamsPost,No parameters POST request";
    return new Result<String>(CodeEnum.RESULT_CODE_SUCCESS, data);
}

The second method: form form and POST value transfer

// Form request parameter mode
// Access address: http://localhost:8080/restful/post/reqFormPOST
@RequestMapping(value="/restful/post/reqFormPOST", method = RequestMethod.POST)
@ResponseBody
public Result<ParamsVO> reqFormPOST(ParamsVO vo) {
    if (vo == null) {
        return new Result<ParamsVO>(CodeEnum.RESULT_CODE_FAIL, new ParamsVO());
    }
    return new Result<ParamsVO>(CodeEnum.RESULT_CODE_SUCCESS, vo);
}


design sketch:

 

The third method: JSON mode, POST request collection parameters

// json mode
// Access address: http://localhost:8080/restful/post/reqBodysParamsPOST
@RequestMapping(value="/restful/post/reqBodysParamsPOST", method = RequestMethod.POST)
@ResponseBody
public Result<List<String>> reqBodysParamsPOST(@RequestBody List<String> ids) {
    if (ids == null || ids.size()==0) {
        return new Result<List<String>>(CodeEnum.RESULT_CODE_FAIL, new ArrayList<String>());
    }
    return new Result<List<String>>(CodeEnum.RESULT_CODE_SUCCESS, ids);
}

The fourth method: JSON mode, POST request object parameters

// json mode
// Access address: http://localhost:8080/restful/post/reqBodysObjectPOST
@RequestMapping(value="/restful/post/reqBodysObjectPOST", method = RequestMethod.POST)
@ResponseBody
public Result<ParamsVO> reqBodysObjectPOST(@RequestBody ParamsVO vo) {
    if (vo == null) {
        return new Result<ParamsVO>(CodeEnum.RESULT_CODE_FAIL, new ParamsVO());
    }
    return new Result<ParamsVO>(CodeEnum.RESULT_CODE_SUCCESS, vo);
}


design sketch:

 

6) Redirection and request forwarding
 

After the project is started, you can directly enter the address in the browser for access.

package com.oysept.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class LocationController {
    
    // Redirect address
    @RequestMapping("/restful/returnMessage")
    @ResponseBody
    public String returnMessage () {
        return "Test redirection or Request forwarding, return message!";
    }
 
    // Test request forwarding address: http://localhost:8080/restful/forward/req
    @RequestMapping("/restful/forward/req")
    public String forwardReq () {
        // There must be no spaces between addresses
        return "forward:/restful/returnMessage";
    }
    
    // Test redirect address: http://localhost:8080/restful/redirect/req
    @RequestMapping("/restful/redirect/req")
    public String redirectReq () {
        // There must be no spaces between addresses
        return "redirect:/restful/returnMessage";
    }
}

7) Attachment download method
This method is suitable for remote downloading of files from various byte streams, including http or https addresses.

Step 1: pass in the HttpServletResponse object.

Step 2: set attachment information, such as attachment name, attachment code, etc.

Step 3: get the ContentType of the attachment. When downloading the attachment, you need to specify the file type converted to. (common types listed)

Step 4: get the remote attachment stream through http or https.

Step 5: download the attachment to the specified local path.

Source code:

package com.oysept.controller;
 
import com.oysept.bean.ParamsVO;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
 
@Controller
public class DownloadController {
    
    // Return the response message, which is suitable for downloading various types of files
    // Request address: http://localhost:8080/restful/file/download
    @RequestMapping(value = "/restful/file/download", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void urlDownload(@RequestBody ParamsVO vo, HttpServletResponse response) {
        // Print parameter information in the object
        System.out.println("id: " + vo.getId() + ", name: " + vo.getName());
        try {
            String filename = "baidu.html";
            // Set the attachment information. If the fileName contains Chinese, garbled code may appear
            response.setHeader("Content-disposition", "attachment; filename=" + URLDecoder.decode(filename, "UTF-8"));
            response.setCharacterEncoding("utf-8");
            response.setContentType(getResponseContentType("html")); // Different file types have different contenttypes. If you need to dynamically specify the type, you can intercept the suffix of the attachment
            
            BufferedInputStream bufferInput = null; // Byte cache input stream
            BufferedOutputStream bufferOutput = null; // Byte cache output stream
            try {
                InputStream in = getHttpInputStream("https://www.baidu.com/", "GET");
                bufferInput = new BufferedInputStream(in);
                
                OutputStream out = response.getOutputStream();
                    bufferOutput = new BufferedOutputStream(out);
                
                int l = -1;
                byte[] tmp =new byte[1024];
                while ((l = bufferInput.read(tmp)) != -1) {
                    bufferOutput.write(tmp, 0, l);
                }
            } catch (FileNotFoundException e) {
                System.out.println("/restful/file/download!" + e);
            } catch (IOException e) {
                System.out.println("/restful/file/download!" + e);
            } finally {
                // Close the low-level flow.
                try {
                    if (bufferInput != null) {
                        bufferInput.close();
                    }
                    if (bufferOutput != null){
                        bufferOutput.close();
                    }
                } catch (IOException e) {
                    System.out.println("/restful/file/download!" + e);
                }
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("/restful/file/download!" + e);
        }
    }
    
    /**
     * Gets the ContentType parameter of the HttpServletResponse setting
     * @return
     */
    public String getResponseContentType(String type) {
        String contentType = null;
        if ("xlsx,xls,docx,doc,pptx,ppt,dotx,docm,dotm,xltx,xlsm,xltm,xlam,xlsb,potx,ppsx,ppam,pptm,potm,ppsm,xlt,xla,pot,pps,ppa"
                .contains(type)) {
            // Attachment header processing
            if("xlsx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
            } else if("xls".equals(type) || "xlt".equals(type) || "xla".equals(type)) {
                contentType = "application/vnd.ms-excel;charset=utf-8";
            } else if("docx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8";
            } else if("doc".equals(type) || "dot".equals(type)) {
                contentType = "application/msword;charset=utf-8";
            } else if("pptx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation;charset=utf-8";
            } else if("ppt".equals(type) || "pot".equals(type) || "pps".equals(type) || "ppa".equals(type)) {
                contentType = "application/vnd.ms-powerpoint;charset=utf-8";
            } else if("dotx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.template;charset=utf-8";
            } else if("docm".equals(type)) {
                contentType = "application/vnd.ms-word.document.macroEnabled.12;charset=utf-8";
            } else if("dotm".equals(type)) {
                contentType = "application/vnd.ms-word.template.macroEnabled.12;charset=utf-8";
            } else if("xltx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.template;charset=utf-8";
            } else if("xlsm".equals(type)) {
                contentType = "application/vnd.ms-excel.sheet.macroEnabled.12;charset=utf-8";
            } else if("xltm".equals(type)) {
                contentType = "application/vnd.ms-excel.template.macroEnabled.12;charset=utf-8";
            } else if("xlam".equals(type)) {
                contentType = "application/vnd.ms-excel.addin.macroEnabled.12;charset=utf-8";
            } else if("xlsb".equals(type)) {
                contentType = "application/vnd.ms-excel.sheet.binary.macroEnabled.12;charset=utf-8";
            } else if("potx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.presentationml.template;charset=utf-8";
            } else if("ppsx".equals(type)) {
                contentType = "application/vnd.openxmlformats-officedocument.presentationml.slideshow;charset=utf-8";
            } else if("ppam".equals(type)) {
                contentType = "application/vnd.ms-powerpoint.addin.macroEnabled.12;charset=utf-8";
            } else if("pptm".equals(type)) {
                contentType = "application/vnd.ms-powerpoint.presentation.macroEnabled.12;charset=utf-8";
            } else if("potm".equals(type)) {
                contentType = "application/vnd.ms-powerpoint.template.macroEnabled.12;charset=utf-8";
            } else if("ppsm".equals(type)) {
                contentType = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12;charset=utf-8";
            }
        } else if ("txt".equals(type)) {
            contentType = "text/plain;charset=utf-8";
        } else if ("pdf".equals(type)) {
            contentType = "application/pdf;charset=utf-8";
        } else if ("png".equals(type)) {
            contentType = "image/png;charset=utf-8";
        } else if ("jpg".equals(type) || "jpeg".equals(type)) {
            contentType = "image/jpeg;charset=utf-8";
        } else if ("bmp".equals(type)) {
            contentType = "application/x-bmp;charset=utf-8";
        } else if ("gif".equals(type)) {
            contentType = "image/gif;charset=utf-8";
        } else if ("html".equals(type) || "htm".equals(type)) {
            contentType = "text/html;charset=utf-8";
        } else if ("xml".equals(type)) {
            contentType = "text/xml;charset=utf-8";
        } else if ("css".equals(type)) {
            contentType = "text/css;charset=utf-8";
        } else if ("js".equals(type)) {
            contentType = "application/x-javascript;charset=utf-8";
        } else if ("eml".equals(type)) {
            contentType = "message/rfc822;charset=utf-8";
        } else if ("xlw".equals(type)) {
            contentType = "application/x-xlw;charset=utf-8";
        } else if ("ai".equals(type)) {
            contentType = "application/postscript;charset=utf-8";
        } else if ("rtf".equals(type)) {
            contentType = "application/msword;charset=utf-8";
        } else if ("mp4".equals(type)) {
            contentType = "video/mpeg4;charset=utf-8";
        } else if ("tif".equals(type) || "tiff".equals(type)) {
            contentType = "image/tiff;charset=utf-8";
        } else if ("exe".equals(type)) {
            contentType = "application/x-msdownload;charset=utf-8";
        } else if ("pls".equals(type)) {
            contentType = "audio/scpls;charset=utf-8";
        } else if ("rpm".equals(type)) {
            contentType = "audio/x-pn-realaudio-plugin;charset=utf-8";
        } else if ("mht".equals(type)) {
            contentType = "message/rfc822;charset=utf-8";
        }
        return contentType;
    }
    
    /**
     * http Get InputStream
     * @param requestUrl: Request path
     * @param requestMethod: Request method (GET, POST)
     * @return
     */
    public InputStream getHttpInputStream(String requestUrl, String requestMethod) {
        HttpURLConnection con = null;
        InputStream is = null;
        try {
            URL url = new URL(requestUrl);
            // Native access http request, no proxy request
            con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestMethod(requestMethod);
            con.setReadTimeout(60000);
            con.setConnectTimeout(60000);
            con.connect();
            // Get InputStream
            is = con.getInputStream();
            return is;
        } catch (IOException e) {
            System.out.println("getHttpInputStream error!" + e);
        }
        return null;
    }
}


Original link: https://blog.csdn.net/p812438109/article/details/106629526

Tags: Java Back-end RESTful

Posted on Fri, 03 Dec 2021 16:00:34 -0500 by keyur.delhi