天天看點

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>