SpringBoot使用教程【1】Restful API设计 返回json,xml格式

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qingfeng812/article/details/74738885

效果展示:

浏览器截图
这里写图片描述

http://localhost:8080/Chapter/getParam/app/xml
这里写图片描述
http://localhost:8080/Chapter/getParam/app/json
这里写图片描述

主要知识点:

  • SpringBoot的使用
  • HTTP Content-type
  • Spring属性produces
  • Restful API (根据不同参数返回不同响应格式)
  • Okhttp的使用

服务器:

源码

package com.didispace.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.didispace.util.HttpRequestUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
  常见的媒体格式类型如下:

    text/html : HTML格式
    text/plain :纯文本格式      
    text/xml :  XML格式
    image/gif :gif图片格式    
    image/jpeg :jpg图片格式 
    image/png:png图片格式

   以application开头的媒体格式类型:

   application/xhtml+xml :XHTML格式
   application/xml     : XML数据格式
   application/atom+xml  :Atom XML聚合格式    
   application/json    : JSON数据格式
   application/pdf       :pdf格式  
   application/msword  : Word文档格式
   application/octet-stream : 二进制流数据(如常见的文件下载)
   application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

   另外一种常见的媒体格式是上传文件之时使用的:

    multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

    以上就是我们在日常的开发中,经常会用到的若干content-type的内容格式。

 * @author Arison
 *
 */
@Api(value = "get请求", description = " ")
@RestController
public class HttpGetController {

    @ApiOperation(value = "默认", notes = "")
    @RequestMapping(value = "/getParam", method = RequestMethod.GET)
    public @ResponseBody Map<String, Object> getParam(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return goods;
    }

    @ApiOperation(value = "text/html", notes = "text/html")
    @RequestMapping(value = "/getParam/html", method = RequestMethod.GET
            , produces = "text/html; charset=utf-8")
    public @ResponseBody Object getParamHtml(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        //注意返回类型需要是Object或者String
        return JSON.toJSONString(goods);
    }

    @ApiOperation(value = "text/plain", notes = "text/plain")
    @RequestMapping(value = "/getParam/text", method = RequestMethod.GET
            , produces = "text/plain; charset=utf-8")
    public @ResponseBody String getParamText(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return JSON.toJSONString(goods);
    }

    @ApiOperation(value = "text/xml", notes = "text/xml")
    @RequestMapping(value = "/getParam/xml", method = RequestMethod.GET
            , produces = "text/xml; charset=utf-8")
    public @ResponseBody Map<String, Object> getParamXml(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return goods;
    }

    @ApiOperation(value = "text/json", notes = "text/json")
    @RequestMapping(value = "/getParam/json", method = RequestMethod.GET
            , produces = "text/json; charset=utf-8")
    public @ResponseBody String getParamJson(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return JSON.toJSONString(goods);
    }

    @ApiOperation(value = "application/json", notes = "application/json")
    @RequestMapping(value = "/getParam/app/json", method = RequestMethod.GET
            , produces = "application/json; charset=utf-8")
    public @ResponseBody Map<String, Object> getParamAppJson(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return goods;
    }

    @ApiOperation(value = "application/xml", notes = "application/xml")
    @RequestMapping(value = "/getParam/app/xml", method = RequestMethod.GET
            , produces = "application/xml; charset=utf-8")
    public @ResponseBody Map<String, Object> getParamAppXml(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return goods;
    }

    @ApiOperation(value = "application/xhtml+xml", notes = "application/xhtml+xml")
    @RequestMapping(value = "/getParam/app/html", method = RequestMethod.GET
            , produces = "application/xhtml+xml ; charset=utf-8")
    public @ResponseBody Map<String, Object> getParamAppHtml(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return goods;
    }

    @ApiOperation(value = "application/text", notes = "application/text")
    @RequestMapping(value = "/getParam/app/text", method = RequestMethod.GET
            , produces = "application/text ; charset=utf-8")
    public @ResponseBody String getParamAppText(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Map<String, Object> goods = HttpRequestUtils.getHttpMessage(request);
        return JSON.toJSONString(goods);
    }
}

客户端调用(Java或Android)

源码

public static final String BASE_URL = "http://192.168.253.200:8080/Chapter/";

    public static HttpClient httpClient = new HttpClient.Builder(BASE_URL)// 根路径
            .header("Cookie", "abdclejdldj82jk23jfjd")// 全局请求头 //局部可累加
            .header("Cache-control", "max-age=600")
            .maxRetryCount(0)// 局部可覆盖
            .isDebug(false)// 局部可覆盖
            .retryTimeout(1000)// 局部可覆盖
            .cacheFile(new File("C:/Cache"))// 局部可覆盖
            .cacheFileSize(10240 * 1024)// 局部可覆盖
            .cacheType(CacheType.ONLY_NETWORK)// 局部可覆盖
            .cacheTime(60 * 200)// 设置10分钟 //局部可覆盖
            .connectTimeout(5000)// 局部可覆盖
            .readTimeout(5000)// 局部可覆盖
            .writeTimeout(7000)// 局部可覆盖
            .httpBase(RetrofitImpl.getInstance())// 局部可覆盖
            .build(true);// 保持单例



        httpClient
                .Api()
                .send(new HttpClient.Builder()
                        .url("getParam")// 子路径
                        .add("param3", "value1")// 局部参数
                        .add("param4", "value2")
                        .header("cookies", "cookies")// 局部请求头
                        .header(
                                "Accept",
                                "text/html,application/json,application/xml;q=0.9,image/webp,*/*;q=0.8")
                        .header("Cookie", "android")// 局部请求头
                        .header("Cookie", "java")// 局部请求头---同名请求会覆盖
                        .header("header3", "header1")// 局部请求头
                        .header("header4", "header2")// 局部请求头

                        .method(Method.GET)
                        .build(), new NetResquestSubscriber<Object>(new SubscriberOnNextListener<Object>() {

                            @Override
                            public void onNext(Object t) {
                                OkhttpUtils.println(t.toString());
                            }
                        }));

截图:
这里写图片描述

总结

  • 本文重点在于控制响应头Content-Type的返回类型,来控制返回xml或者json格式。
  • Springboot本身需要集成jackson-dataformat-xml来支持xml格式输出,否则会报406错误
        <!-- xml输出 -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
相关文章
|
9天前
|
安全 Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+jsp实现的健身房管理系统(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和JSP技术实现的健身房管理系统。随着健康生活观念的普及,健身房成为日常锻炼的重要场所,高效管理会员信息、课程安排等变得尤为重要。该系统旨在通过简洁的操作界面帮助管理者轻松处理日常运营挑战。技术栈包括:JDK 1.8、Maven 3.6、MySQL 8.0、JSP、Shiro、Spring Boot 2.0等。系统功能覆盖登录、会员管理(如会员列表、充值管理)、教练管理、课程管理、器材管理、物品遗失管理、商品管理及信息统计等多方面。
|
7天前
|
JavaScript Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的考试管理系统(含教程&源码&数据库数据)
在数字化时代背景下,本文详细介绍了如何使用Spring Boot框架结合Vue.js技术栈,实现一个前后端分离的考试管理系统。该系统旨在提升考试管理效率,优化用户体验,确保数据安全及可维护性。技术选型包括:Spring Boot 2.0、Vue.js 2.0、Node.js 12.14.0、MySQL 8.0、Element-UI等。系统功能涵盖登录注册、学员考试(包括查看试卷、答题、成绩查询等)、管理员功能(题库管理、试题管理、试卷管理、系统设置等)。
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的考试管理系统(含教程&源码&数据库数据)
|
9天前
|
JavaScript API PHP
一言API搭建教程:搭建属于自己的文言API接口
这篇文章介绍了如何搭建一个属于自己的文言API接口。文章首先介绍了准备工作,包括代码编辑器和两个文件的创建。然后详细说明了如何将代码复制到php文件中并上传至网站根目录。最后给出了一个示例代码来调用文言API接口。整个过程非常简单。
24 1
|
12天前
|
JavaScript Java Maven
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和Vue.js实现的在线求职平台。该平台采用了前后端分离的架构,使用Spring Boot作为后端服务
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
|
16天前
|
XML JSON Java
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
本文介绍了如何使用IntelliJ IDEA和Maven搭建一个整合了Struts2、Spring4、Hibernate4的J2EE项目,并配置了项目目录结构、web.xml、welcome.jsp以及多个JSP页面,用于刷新和学习传统的SSH框架。
27 0
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
UnityWebRequest教程☀️2021,你还在使用过时的 www API吗?
UnityWebRequest教程☀️2021,你还在使用过时的 www API吗?
|
20天前
|
开发框架 .NET API
在IIS上部署ASP.NET Core Web API和Blazor Wasm详细教程
在IIS上部署ASP.NET Core Web API和Blazor Wasm详细教程
|
22天前
|
API 数据库 索引
indexedDB 操作库IDBWRAPPER 教程翻译及API翻译第二部分part2
indexedDB 操作库IDBWRAPPER 教程翻译及API翻译第二部分part2
|
3天前
|
SQL Shell API
python Django教程 之 模型(数据库)、自定义Field、数据表更改、QuerySet API
python Django教程 之 模型(数据库)、自定义Field、数据表更改、QuerySet API
|
2月前
|
存储 JSON 数据格式
Python教程:json中load和loads的区别
【7月更文挑战第17天】在Python的`json`模块中, `load`与`loads`函数均用于JSON至Python对象的转换, 区别在于: - **`loads`**处理JSON格式的**字符串** 其中`data.json`文件内容为`{&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}`。 简而言之, `loads`用于字符串, 而`load`用于文件对象。根据数据来源选择合适的方法。
下一篇
云函数