当前位置: 首页 > 知识库问答 >
问题:

Springfox 404从Swagger UI测试API时出错

黄逸清
2023-03-14

调查Springfox和Swagger UI,但我面临一个问题。我正在使用Spring Boot REST示例项目作为我的PoC的基础。我正在运行JDK8,项目利用Gradle。

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.7.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-rest-service'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
    jcenter()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("io.springfox:springfox-swagger2:2.2.2")
    compile("io.springfox:springfox-swagger-ui:2.2.2")
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}
package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}
package hello;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}
package hello;

import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.schema.AlternateTypeRules.newRule;

import java.time.LocalDate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.async.DeferredResult;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.fasterxml.classmate.TypeResolver;

@SpringBootApplication
@EnableSwagger2
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    private TypeResolver typeResolver;

    @Bean
    public Docket greetingApi() {
        return new Docket(DocumentationType.SPRING_WEB)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .pathMapping("/")
            .directModelSubstitute(LocalDate.class, String.class)
            .genericModelSubstitutes(ResponseEntity.class)
            .alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class,
                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                typeResolver.resolve(WildcardType.class)))
            .useDefaultResponseMessages(false)
            .globalResponseMessage(RequestMethod.GET,
                newArrayList(new ResponseMessageBuilder()
                    .code(500)
                    .message("500 message")
                    .responseModel(new ModelRef("Error"))
                    .build()))
            .enableUrlTemplating(true);
    }

}
Response Class (Status 200)

Model

{
  "content": "string",
  "id": 0
}

Response Content Type: */*

Parameters
parameter = name, value = World, parameter type = query, data type = string

当我点击“试用”按钮时,我看到了以下内容:

curl = curl -X GET --header "Accept: */*" "http://localhost:8080/greeting{?name}?name=World"

request url = http://localhost:8080/greeting{?name}?name=World

repsonse body = {
  "timestamp": 1446418006199,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/greeting%7B"
}

response code = 404

response headers = {
  "server": "Apache-Coyote/1.1",
  "content-type": "application/json;charset=UTF-8",
  "transfer-encoding": "chunked",
  "date": "Sun, 01 Nov 2015 22:46:46 GMT"
}

乍一看,由于某种原因,SpringFox/Swagger似乎没有正确地替换{?Name}的占位符。我的问题是,我如何配置它这样做,如果这是事实上的问题,以便我可以成功地测试服务从Swagger UI页面?

共有1个答案

文建业
2023-03-14

application类中,将enableurltemplating更改为false将解决问题。

@Bean
public Docket greetingApi() {
    return new Docket(DocumentationType.SPRING_WEB)
        //...
        .enableUrlTemplating(false);
}

只是那面旗帜上的一点背景。该标志是为了支持RFC6570,没有RFC6570,仅有查询字符串参数差异的操作将无法按照规范正确显示。在swagger规范的下一个迭代中,有计划解决这个问题。这就是enableurltemplating被标记为孵化特性的原因。

 类似资料:
  • SwaggerUI 汉化版;修改了部分样式;结合SpringFox SpringFox-Swagger-UI实现API管理

  • 我想在Rest API(spring-mvc)文档中使用Springfox SwaggerUI。我在@RequestMapping注释中使用版本头,但是如果我有相同方法的两个版本,在SwaggerUI中只能看到一个。 上面的代码导致api文档中只有一个可见的方法。 考虑到我的版本头,是否有任何选项可以将Swagger配置为不同的endpoint?

  • 我在Angular 12中运行ng测试时遇到以下问题: NullInjectorError:R3Injector错误(DynamicTestModule)[BaseURL- 错误:未定义应为true。位于UserContext。(http://localhost:9876/karma_webpack/webpack:/src/app/menu/menu.component.spec.ts:46:2

  • API(Application Programming Interface)测试的自动化是软件测试最基本的一种类型。从本质上来说,API 测试是用来验证组成软件的那些单个方法的正确性,而不是测试整个系统本身。API 测试也称为单元测试(Unit Testing)、模块测试(Module Testing)、组件测试(Component Testing)以及元件测试(Element Testing)。

  • 我有一个应用程序(使用注释的Spring 4 MVC Hibernate 4 MySQL Maven集成示例),使用基于注释的配置将Spring与Hibernate集成,但运行测试时出错! 上课时间到了 下面是即将到来的考验: 这是pom。xml文件:

  • 我正在处理APK扩展文件,我查看了以下链接: 1)创建APK扩展文件的步骤 2)http://ankitthakkar90.blogspot.in/2013/01/apk-expansion-files-in-android-with.html 我已经从path sdk path/extras/google导入了market_许可、play_apk_扩展 play_apk_扩展包含三个项目down