springboot add request header (swagger)
Application: When using swagger ui to test the interface, you can add headers for related tests
*****************************
Examples
*********************
config layer
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 layer
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(@RequestHeader("header_name") String value){
System.out.println(value);
return "hello world "+value;
}
}
***********************
Use test
localhost:8080/swagger-ui.html
Note: The value of header cannot be Chinese, otherwise an error will be reported Failed to execute 'fetch' on 'Window': Value is not a valid ByteString.