springboot 添加请求头(swagger)


springboot 添加请求头(swagger)

应用:使用swagger ui测试接口时,可添加header进行相关测试

*****************************

示例

*********************

config 层

Swagger2Config

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket initDocket(){
        List<Parameter> params=new ArrayList<>();
        Parameter header=new ParameterBuilder().name("header_name").description("请求头")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).defaultValue("gtlx").build();
        params.add(header);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(initApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(params);
    }

    private ApiInfo initApiInfo(){
        return new ApiInfoBuilder()
                .title("构建 swagger2")
                .description("接口测试")
                .termsOfServiceUrl("http://www.baidu.com")
                .version("v1.0")
                .build();
    }
}

*********************

controller 层

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(@RequestHeader("header_name") String value){
        System.out.println(value);

        return "hello world "+value;
    }
}

***********************

使用测试

localhost:8080/swagger-ui.html

      

      

      

      

说明:header的值不能为中文,否则会报错 Failed to execute 'fetch' on 'Window': Value is not a valid ByteString.

发布了387 篇原创文章 · 获赞 98 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43931625/article/details/105003926