当前位置: 首页 > news >正文

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

版权声明:本文为博主原创文章,未经博主允许不得转载。 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>

相关文章:

  • weblogic部署web项目出现错误
  • 自制字幕遮挡器
  • CYQ.Data 轻量数据层之路 抢先体验版本功能说明演示 (二十九)
  • 性能测试解惑之并发压力
  • AWS CTO:“我真心讨厌跟软件工具供应商打交道”
  • 思科发现英特尔集成显卡驱动存在安全漏洞 可任意执行代码
  • 为何科技独角兽接连上市
  • 秒表---框架搭建
  • 【转】maven命令-P 参数引发的思考
  • Chapter3_操作符_关系操作符
  • 安全抽象:网络安全生态系统从复杂臃肿到有效自动化的发展之道
  • loadrunner
  • Linux 添加硬盘设备
  • 阿里云oss教程
  • 2013-2014年度总结
  • @jsonView过滤属性
  • [ 一起学React系列 -- 8 ] React中的文件上传
  • 【Linux系统编程】快速查找errno错误码信息
  • Apache Pulsar 2.1 重磅发布
  • Django 博客开发教程 16 - 统计文章阅读量
  • Docker容器管理
  • Elasticsearch 参考指南(升级前重新索引)
  • Fabric架构演变之路
  • mysql innodb 索引使用指南
  • React组件设计模式(一)
  • Shell编程
  • 关于 Cirru Editor 存储格式
  • 关于 Linux 进程的 UID、EUID、GID 和 EGID
  • 精彩代码 vue.js
  • 开发基于以太坊智能合约的DApp
  • 排序(1):冒泡排序
  • 排序算法之--选择排序
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 少走弯路,给Java 1~5 年程序员的建议
  • 手机端车牌号码键盘的vue组件
  • LevelDB 入门 —— 全面了解 LevelDB 的功能特性
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • 数据可视化之下发图实践
  • ​Spring Boot 分片上传文件
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • $L^p$ 调和函数恒为零
  • $refs 、$nextTic、动态组件、name的使用
  • (2022版)一套教程搞定k8s安装到实战 | RBAC
  • (SpringBoot)第七章:SpringBoot日志文件
  • (博弈 sg入门)kiki's game -- hdu -- 2147
  • (动手学习深度学习)第13章 计算机视觉---微调
  • (官网安装) 基于CentOS 7安装MangoDB和MangoDB Shell
  • (四) Graphivz 颜色选择
  • (转)甲方乙方——赵民谈找工作
  • (转)拼包函数及网络封包的异常处理(含代码)
  • (轉貼) VS2005 快捷键 (初級) (.NET) (Visual Studio)
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .NET/C# 异常处理:写一个空的 try 块代码,而把重要代码写到 finally 中(Constrained Execution Regions)
  • .NET/C# 阻止屏幕关闭,阻止系统进入睡眠状态
  • @FeignClient 调用另一个服务的test环境,实际上却调用了另一个环境testone的接口,这其中牵扯到k8s容器外容器内的问题,注册到eureka上的是容器外的旧版本...