首页 > 解决方案 > 在 HTTP GET 请求上添加查询参数时出现 UnsupportedMediaException?

问题描述

我正在使用 Spring 的 WebClient 来调用第三方 api,并且正在使用 Wiremock 来模拟 API 调用。

我有以下课程

public TokenResponse {
   private String responseStatus;
   private String failureTrace;
   private String token;
}

这是我的 Wiremock 文件:

{
    "request": {
        "method": "GET",
        "urlPattern": "/some-uri",
        "headers": {
            "Content-Type": {
                "equalTo": "application/json"
            },
            "Accept": {
                "equalTo": "application/json"
            }
        }
    },
    "response": {
        "status": 200,
        "jsonBody": {
            "responseStatus": "SUCCESS",
            "failureTrace": "",
            "token": "my token"
        },
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

当在没有任何查询参数的情况下调用 webclient 时GET /some-uri,一切正常。我得到一个带有正确令牌的 200。

当我像这样更改我的存根文件时:

{
    "request": {
        "method": "GET",
        "urlPattern": "/some-uri",
        "queryParameters": {
            "id": {
                "equalTo": "myLogin"
            }
        },
        "headers": {
            "Content-Type": {
                "equalTo": "application/json"
            },
            "Accept": {
                "equalTo": "application/json"
            }
        }
    },
    "response": {
        "status": 200,
        "jsonBody": {
            "responseStatus": "SUCCESS",
            "failureTrace": "",
            "token": "mon token"
        },
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

我像这样更改uri : GET /some-uri?id=myLogin,然后我收到以下错误:

404 Not Found from GET http://localhost:8091/some-uri; nested exception is org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/plain' not supported for bodyType=fr.dto.TokenResponse)\)

这是我的 Webclient 的设置方式:

 protected WebClient client = WebClient.create(this.getBaseUrl());

    protected ResponseSpec create(String uri, HttpMethod method){
        return client.method(method)
            .uri(uri)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxClientError, this::handle4xxError)
            .onStatus(HttpStatus::is4xxClientError, this::handle5xxError);
    }

标签: webclientwiremock

解决方案


推荐阅读