【问题标题】:Spring rest template get for entity giving 400 errorSpring rest模板获取实体给出400错误
【发布时间】:2018-12-01 05:12:40
【问题描述】:

我收到以下异常org.springframework.web.client.HttpClientErrorException: 400 Bad Request

关于此声明final ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:12001/api/profiles/bymsisdn/0747894146", String.class);

但我正在使用 curl url -X GET "http://localhost:8001/api/profiles/bymsisdn/0747894146"

补充说明: resttemplate = new RestTemplate(); // No Headers or extra convertors added as I think it's not required because using curl works fine

【问题讨论】:

标签: java spring spring-rest


【解决方案1】:

您可以使用requestbin 来测试您的http 客户端的执行情况。

我认为 RestTemplate 将 Accept 标头放入您的服务器响应 400。因此您可能需要编辑您的请求标头:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
restTemplate.exchange("http://localhost:12001/api/profiles/bymsisdn/0747894146", HttpMethod.GET, entity, String.class);

请注意,这是一个暂定的解决方案,请适应您的服务器。

【讨论】:

  • 我在发布问题之前已经尝试过了。不走运谢谢
【解决方案2】:

curl 使用 / 作为 Accept 标头,当您未指定时。如果您没有指定接受标头,则使用 RestTemplate ,它会尝试为您的响应类型(在您的情况下为字符串)找到合适的 MIME 类型。对于 String 类,取决于您的配置,它可以匹配 text/* MIME 类型,这些类型可能与目标端点生成的内容不匹配。

尝试使用 RestTemplate 的交换重载方法明确指定需要处理的内容类型

【讨论】:

    【解决方案3】:

    最终字符串 uri = http://localhost:8088/myapp/{data}";

    RestTemplate restTemplate = new RestTemplate();

    MyResponse 结果 = restTemplate.getForObject(uri,MyResponse.class,valData);

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多