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

Spring WebFlux WebClient-如何解决400个错误请求

万俟皓
2023-03-14

我是反应性编程的新手,我正在使用Spring WebFlux的WebClient向下面的URL发出POST请求,作为Spring Boot应用程序的一部分,将现有的测验分配给候选人。我很难理解我在构造WebClient请求时做错了什么。

终点

{
   "quiz_id": ""
}

quizrequest.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class QuizRequest {

  @JsonProperty("quiz_id")
  @NotBlank
  private String quizId;

  public QuizRequest(@NotBlank String quizId) {
    this.quizId = quizId;
  }
}

java FlexiQuizClient.java

@Service
@Slf4j
public class FlexiQuizClient {

  private static final String USER_AGENT = "WebClient for FlexiQuiz";

  private final WebClient webClient;

  @Value("${flexiquiz.baseurl}")
  private String FLEXIQUIZ_API_BASE_URL;

  @Value("${flexiquiz.key}")
  private String FLEXIQUIZ_API_KEY;

  @Autowired
  public FlexiQuizClient() {
    this.webClient = WebClient.builder()
        .baseUrl(FLEXIQUIZ_API_BASE_URL)
        .defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
        .filter(logRequest())
        .build();
  }

  public String assignQuizToCandidate(String userId, QuizRequest quizRequest) {
    return Objects.requireNonNull(webClient.post()
        .uri(FLEXIQUIZ_API_BASE_URL + "/v1/users/" + userId + "/quizzes")
        .header("X-API-KEY", FLEXIQUIZ_API_KEY)
        .body(Mono.just(quizRequest), QuizRequest.class)
        .exchange()
        .block())
        .bodyToMono(String.class)
        .block();
  }

  private ExchangeFilterFunction logRequest() {
    return (clientRequest, next) -> {
      log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
      clientRequest.headers()
          .forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
      return next.exchange(clientRequest);
    };
  }
}

在我的资源类(控制器)中,我调用web客户端方法,如下所示:

private String assignQuizToCandidate(String userId, QuizRequest quizRequest)
      throws ParseException {
    log.info("Assigning a quiz based on your skill");
    String message = quizClient.assignQuizToCandidate(userId, quizRequest);
    log.info("message from status: " + message);
    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(message);
    return (String) json.get("message");
}
QuizRequest quizRequest = new QuizRequest(openQuiz.get().getQuizId());
String status = assignQuizToCandidate(userId, quizRequest);
2020-05-17 10:20:09.938 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Channel acquired, now 1 active connections and 0 inactive connections
2020-05-17 10:20:09.938 DEBUG 32600 --- [ctor-http-nio-1] r.netty.http.client.HttpClientConnect    : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Handler is being applied: {uri=https://www.flexiquiz.com/api/v1/users/{userid}/quizzes, method=POST}
2020-05-17 10:20:09.939 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] onStateChange(POST{uri=/api/v1/users/{userid}/quizzes, connection=PooledConnection{channel=[id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443]}}, [request_prepared])
2020-05-17 10:20:09.939 DEBUG 32600 --- [ctor-http-nio-1] o.s.http.codec.json.Jackson2JsonEncoder  : [1bbedd72] Encoding [QuizRequest(quizId={quizid})]
2020-05-17 10:20:09.941 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] onStateChange(POST{uri=/api/v1/users/{userid}/quizzes, connection=PooledConnection{channel=[id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443]}}, [request_sent])
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.http.client.HttpClientOperations     : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Received response (auto-read:false) : [Cache-Control=private, Content-Type=text/html; charset=utf-8, Server=Microsoft-IIS/10.0, Date=Sun, 17 May 2020 04:50:10 GMT, Content-Length=30]
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] onStateChange(POST{uri=/api/v1/users/{userid}/quizzes, connection=PooledConnection{channel=[id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443]}}, [response_received])
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] o.s.w.r.f.client.ExchangeFunctions       : [1bbedd72] Response 400 BAD_REQUEST
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.http.client.HttpClientOperations     : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Received last HTTP packet
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] onStateChange(POST{uri=/api/v1/users/{userid}/quizzes, connection=PooledConnection{channel=[id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443]}}, [response_completed])
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] onStateChange(POST{uri=/api/v1/users/{userid}/quizzes, connection=PooledConnection{channel=[id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443]}}, [disconnecting])
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Releasing channel
2020-05-17 10:20:10.189 DEBUG 32600 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Channel cleaned, now 0 active connections and 1 inactive connections
2020-05-17 10:20:10.190 DEBUG 32600 --- [ctor-http-nio-1] reactor.netty.channel.FluxReceive        : [id: 0x2b404095, L:/192.168.0.106:62197 - R:www.flexiquiz.com/208.117.41.204:443] Subscribing inbound receiver [pending: 1, cancelled:false, inboundDone: true]
2020-05-17 10:20:10.190 DEBUG 32600 --- [ctor-http-nio-1] o.s.core.codec.StringDecoder             : [1bbedd72] Decoded "{"message":"400: Bad Request"}"
2020-05-17 10:20:10.190  INFO 32600 --- [nio-8086-exec-6] i.d.ivrauto.resource.ResponseResource    : message from status: {"message":"400: Bad Request"}
2020-05-17 10:20:10.190  INFO 32600 --- [nio-8086-exec-6] i.d.ivrauto.resource.ResponseResource    : json.get(message): 400: Bad Request
2020-05-17 10:20:10.190  INFO 32600 --- [nio-8086-exec-6] o.h.e.i.AbstractFlushingEventListener    : Processing flush-time cascades
2020-05-17 10:20:10.195 DEBUG 32600 --- [nio-8086-exec-6] o.h.e.i.AbstractFlushingEventListener    : Dirty checking collections
POST: /v1/users/{user_id}/quizzes
$ curl https://www.flexiquiz.com/api/v1/users/06e3244f-1381-4da4-aa75-996981b42edb/quizzes 
-H "X-API-KEY: fcb5f59c-2a2f-44a9-8261-33cbfa97be99"
-d quiz_id="1153af46-9580-4672-af78-f23ce2577a14"

示例响应

{                             
    "message": "200: OK"
}

共有1个答案

百里泓
2023-03-14

您的问题可能是您以错误的格式发送数据。您将以application/json格式在正文中发布数据

但是如果您查看请求,它是使用curl中的-d标志发出的。

来自curl文档:

因此,您的代码应该看起来像这样(某种程度上):

public QuizResponse assignQuizToCandidate(String userId, String quizId) {

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("quiz_id", quizId);

    return webClient.post()
        .uri(FLEXIQUIZ_API_BASE_URL + "/v1/users/" + userId + "/quizzes")
        .header("X-API-KEY", FLEXIQUIZ_API_KEY)
        .bodyValue(formData)
        .retrive()
        .bodyToMono(QuizResponse.class)
        .block();
}
 类似资料:
  • 我有一个基于Spring Web model view controller(MVC)框架的项目。Spring Web模型-视图-控制器(MVC)框架的版本是3.2.8 我有这个控制器 这个URL一切正常:

  • 目前从Angular JS controller中,我试图将JSON数据发送到后端服务。但是我有400个错误的请求错误。 在Controller中,我试图通过http服务发送数据,如下所示:

  • 我已经把swagger融入了我的春装项目中。所有swaggerendpoint都工作正常,但< code >/product/swagger-ui . html 给出400错误。 在我的application.properties文件中,我使用了< code > server . context path =/product 。 在我的控制器中,我有以下映射,我认为这些映射导致了错误。 产品控制者

  • 目标是通过ajax将对象发送到另一台服务器,这是我为CORS设置的,下面是代码。ajax代码片段: 正确发布数据,但使用

  • 我正在尝试搜索亚马逊的产品广告,并使用botlenose来帮助我做到这一点。但是,我刚刚收到HTTP错误400。 其他一些重要信息: 我来自巴西,我的标签也来自亚马逊。这是个问题吗? 我确实检查了我的钥匙、秘密和标签,一切正常。我确实在StackOverflow上查看了其他一些问题,但对我来说没有任何效果。 当然,出于安全原因,我更改了密钥。 Traceback(最近一次调用最后一次):File"

  • 当试图将图像上传到我的服务时,我在Jersey和中有一个非常奇怪的行为。我的服务在DropWizard上运行。 接受图像(以及元数据对象)的方法如下所示: 如果我尝试使用绝对路径上传一个文件,这实际上是有效的!但是,它不工作,我试图上传一个文件使用相对路径。 更重要的是,当服务部署在另一台机器上(上传映像请求来自不同的机器)时,它也不起作用。这很重要,因为我将服务部署到Heroku,我需要从其他地