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>
相关文章
|
8天前
|
安全 Java API
RESTful API设计与实现:Java后台开发指南
【4月更文挑战第15天】本文介绍了如何使用Java开发RESTful API,重点是Spring Boot框架和Spring MVC。遵循无状态、统一接口、资源标识和JSON数据格式的设计原则,通过创建控制器处理HTTP请求,如示例中的用户管理操作。此外,文章还提及数据绑定、验证、异常处理和跨域支持。最后,提出了版本控制、安全性、文档测试以及限流和缓存的最佳实践,以确保API的稳定、安全和高效。
|
11天前
|
小程序 前端开发 API
小程序全栈开发中的RESTful API设计
【4月更文挑战第12天】本文探讨了小程序全栈开发中的RESTful API设计,旨在帮助开发者理解和掌握相关技术。RESTful API基于REST架构风格,利用HTTP协议进行数据交互,遵循URI、客户端-服务器架构、无状态通信、标准HTTP方法和资源表述等原则。在小程序开发中,通过资源建模、设计API接口、定义资源表述及实现接口,实现前后端高效分离,提升开发效率和代码质量。小程序前端利用微信API与后端交互,确保数据流通。掌握这些实践将优化小程序全栈开发。
|
20天前
|
前端开发 Java API
构建RESTful API:Java中的RESTful服务开发
【4月更文挑战第3天】本文介绍了在Java环境中构建RESTful API的重要性及方法。遵循REST原则,利用HTTP方法处理资源,实现CRUD操作。在Java中,常用框架如Spring MVC简化了RESTful服务开发,包括定义资源、设计表示层、实现CRUD、考虑安全性、文档和测试。通过Spring MVC示例展示了创建RESTful服务的步骤,强调了其在现代Web服务开发中的关键角色,有助于提升互操作性和用户体验。
构建RESTful API:Java中的RESTful服务开发
|
24天前
|
XML JSON 安全
谈谈你对RESTful API设计的理解和实践。
RESTful API是基于HTTP协议的接口设计,通过URI标识资源,利用GET、POST、PUT、DELETE等方法操作资源。设计注重无状态、一致性、分层、错误处理、版本控制、文档、安全和测试,确保易用、可扩展和安全。例如,`/users/{id}`用于用户管理,使用JSON或XML交换数据,提升系统互操作性和可维护性。
18 4
|
26天前
|
安全 API 开发者
构建高效可扩展的RESTful API服务
在数字化转型的浪潮中,构建一个高效、可扩展且易于维护的后端API服务是企业竞争力的关键。本文将深入探讨如何利用现代后端技术栈实现RESTful API服务的优化,包括代码结构设计、性能调优、安全性强化以及微服务架构的应用。我们将通过实践案例分析,揭示后端开发的最佳实践,帮助开发者提升系统的响应速度和处理能力,同时确保服务的高可用性和安全。
26 3
|
1月前
|
缓存 前端开发 API
构建高效可扩展的RESTful API:后端开发的最佳实践
【2月更文挑战第30天】 在现代Web应用和服务端架构中,RESTful API已成为连接前端与后端、实现服务间通信的重要接口。本文将探讨构建一个高效且可扩展的RESTful API的关键步骤和最佳实践,包括设计原则、性能优化、安全性考虑以及错误处理机制。通过这些实践,开发者可以确保API的健壮性、易用性和未来的可维护性。
|
1月前
|
API 开发者 UED
深入探讨RESTful API设计原则及最佳实践
在当今互联网时代,RESTful API已成为各种软件系统之间进行通信的重要方式。本文将从资源定义、URI设计、HTTP方法选择、状态码规范等方面深入探讨RESTful API设计的原则与最佳实践,帮助开发者更好地构建高效、健壮的API。
|
12天前
|
XML Java 数据库连接
mybatis中在xml文件中通用查询结果列如何使用
mybatis中在xml文件中通用查询结果列如何使用
9 0
|
14天前
|
XML JavaScript 前端开发
xml文件使用及解析
xml文件使用及解析
|
1月前
|
XML C# 数据格式
使用C#操作XML文件
使用C#操作XML文件
11 0

热门文章

最新文章