【问题标题】:Getting 400 for Spring RestTemplate POST为 Spring RestTemplate POST 获得 400
【发布时间】:2018-06-05 18:49:29
【问题描述】:

在 Spring Boot 应用程序中使用 resttempalate 进行 POST 调用时出现 400 错误。

这是我的代码:

     HttpHeaders headers = new HttpHeaders();
     headers.setContentType(MediaType.APPLICATION_JSON);
     headers.add("Accept", "application/json");
     request = "{ json : string }";
     url = "http://localhost:9082/restws";
     HttpEntity<String> entity = new HttpEntity<String>(request , headers);
     return restTemplate.postForObject(url, entity, String.class);

堆栈跟踪:

org.springframework.web.client.HttpClientErrorException: 400 在 org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63) 在 org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700) 在 org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653) 在 org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613) 在 org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:380) 在 com.envision.application.web.rest.EngineResource.getModelParams(EngineResource.java:109) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(未知来源) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(未知来源) 在 java.lang.reflect.Method.invoke(未知来源) 在 org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)

2018-06-05 14:26:58.064 错误 42744 --- [XNIO-13 task-38] c.e.a.w.rest.errors.ExceptionTranslator:发生意外错误:400 2018-06-05 14:26:58.069 WARN 42744 --- [XNIO-13 task-38] .m.m.a.ExceptionHandlerExceptionResolver:已解决由处理程序执行引起的异常:org.springframework.web.client.HttpClientErrorException:400

【问题讨论】:

  • 你能分享更多代码吗?

标签: java spring spring-boot resttemplate


【解决方案1】:

它不是一个有效的 json。用双引号将键和值括起来。

【讨论】:

  • 我确实发布了实际的 json。我确实尝试过使用有效的 json。
【解决方案2】:

您正在形成一个错误的请求,请尝试更改请求正文。

String request = " {  \"json\" : \"string\" }" ;

【讨论】:

  • 我确实发布了实际的 json。我确实尝试过使用有效的 json。
  • 你能分享一下你尝试消费的服务的规格吗
【解决方案3】:

现在可以了。静止端点的 JSON 解析器需要在字段名称周围加上双引号。感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2019-05-19
    • 2015-05-05
    • 2014-05-14
    • 1970-01-01
    • 2014-12-26
    相关资源
    最近更新 更多