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>
相关文章
|
1月前
|
JSON 数据可视化 API
Python 中调用 DeepSeek-R1 API的方法介绍,图文教程
本教程详细介绍了如何使用 Python 调用 DeepSeek 的 R1 大模型 API,适合编程新手。首先登录 DeepSeek 控制台获取 API Key,安装 Python 和 requests 库后,编写基础调用代码并运行。文末包含常见问题解答和更简单的可视化调用方法,建议收藏备用。 原文链接:[如何使用 Python 调用 DeepSeek-R1 API?](https://apifox.com/apiskills/how-to-call-the-deepseek-r1-api-using-python/)
|
21天前
|
人工智能 API 开发工具
【重磅发布】 免费领取阿里云百炼AI大模型100万Tokens教程出炉,API接口实战操作,DeepSeek-R1满血版即刻体验!
阿里云百炼是一站式大模型开发及应用构建平台,支持开发者和业务人员轻松设计、构建大模型应用。通过简单操作,用户可在5分钟内开发出大模型应用或在几小时内训练专属模型,专注于创新。
472 88
【重磅发布】 免费领取阿里云百炼AI大模型100万Tokens教程出炉,API接口实战操作,DeepSeek-R1满血版即刻体验!
|
3天前
|
XML JSON API
Understanding RESTful API and Web Services: Key Differences and Use Cases
在现代软件开发中,RESTful API和Web服务均用于实现系统间通信,但各有特点。RESTful API遵循REST原则,主要使用HTTP/HTTPS协议,数据格式多为JSON或XML,适用于无状态通信;而Web服务包括SOAP和REST,常用于基于网络的API,采用标准化方法如WSDL或OpenAPI。理解两者区别有助于选择适合应用需求的解决方案,构建高效、可扩展的应用程序。
|
24天前
|
机器学习/深度学习 人工智能 Serverless
👉「免费满血DeepSeek实战-联网搜索×Prompt秘籍|暨6平台横评」
满血 DeepSeek 免费用!支持联网搜索!创作声明:真人攥写-非AI生成,Written-By-Human-Not-By-AI
2540 9
👉「免费满血DeepSeek实战-联网搜索×Prompt秘籍|暨6平台横评」
|
5天前
|
机器学习/深度学习 设计模式 API
Python 高级编程与实战:构建 RESTful API
本文深入探讨了使用 Python 构建 RESTful API 的方法,涵盖 Flask、Django REST Framework 和 FastAPI 三个主流框架。通过实战项目示例,详细讲解了如何处理 GET、POST 请求,并返回相应数据。学习这些技术将帮助你掌握构建高效、可靠的 Web API。
|
1月前
|
缓存 自然语言处理 安全
快速调用 Deepseek API!【超详细教程】
Deepseek 强大的功能,在本教程中,将指导您如何获取 DeepSeek API 密钥,并演示如何使用该密钥调用 DeepSeek API 以进行调试。
|
1月前
|
存储 人工智能 安全
如何调用 DeepSeek-R1 API ?图文教程
首先登录 DeepSeek 开放平台,创建并保存 API Key。接着,在 Apifox 中设置环境变量,导入 DeepSeek 提供的 cURL 并配置 Authorization 为 `Bearer {{API_KEY}}`。通过切换至正式环境发送请求,可实现对话功能,支持流式或整体输出。
1847 15
|
2月前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
13天前
|
JSON JavaScript 前端开发
处理从API返回的JSON数据时返回Unicode编码字符串怎么处理
在处理API返回的JSON数据时,遇到类似`\u7f51\u7edc\u8fde\u63a5\u9519\u8bef`的Unicode编码字符串,可使用JavaScript内置方法转换为可读文字。主要方法包括:1. 使用`JSON.parse`自动解析;2. 使用`decodeURIComponent`和`escape`组合解码;3. 在API调用中直接处理响应数据。这些方法能有效处理多语言内容,确保正确显示非ASCII字符。
|
18天前
|
JSON API 数据格式
淘宝商品评论数据API接口详解及JSON示例返回
淘宝商品评论数据API接口是淘宝开放平台提供的一项服务,旨在帮助开发者通过编程方式获取淘宝商品的评论数据。这些数据包括评论内容、评论时间、评论者信息、评分等,对于电商分析、用户行为研究、竞品分析等领域都具有极高的价值。

热门文章

最新文章