Отправка строки в REST-контроллер Spring (Джексона) методом POST - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь отправить объект String в службу отдыха, используя метод HTTP Post. и строка должна быть отправлена ​​в теле запроса.

Контроллер

@RestController
@RequestMapping(value = "post", method = RequestMethod.POST)
public class HttpMethodPostController {

    /*HttpClientErrorException: 415 null*/
    @RequestMapping(value = "/string_as_text", consumes = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<Void> getStringAsText(@RequestBody String text) {
        System.out.println("[Server] text = " + text);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

    /*HttpClientErrorException: 400 null*/
    @RequestMapping(value = "/string_as_json", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Void> getStringAsJSON(@RequestBody String text) {
        System.out.println("[Server] text = " + text);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

    @RequestMapping(value = "/type1_", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Void> postType1_(@RequestBody Type1_ type1_) {
        System.out.println("[Server] type1_ = " + type1_);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

}

Потребитель

public class HttpMethodPostConsumer {
    public static final String POST_ADDRESS = "http://localhost:55055/post";

    /*HttpClientErrorException: 415 null*/
    public static void postStringAsText(String text) {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        final HttpEntity<String> entity = new HttpEntity<>(text, headers);
        final URI uri = restTemplate.postForLocation(POST_ADDRESS + "/string_as_text", entity, String.class);
        System.out.println("uri = " + uri);
    }

    /*HttpClientErrorException: 400 null*/
    public static void postStringAsJSON(String text) {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        final HttpEntity<String> entity = new HttpEntity<>(text, headers);
        final URI uri = restTemplate.postForLocation(POST_ADDRESS + "/string_as_json", entity, String.class);
        System.out.println("uri = " + uri);
    }

    public static void postType1_(Type1_ type1_) {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        final HttpEntity<Type1_> httpEntity = new HttpEntity<Type1_>(type1_, headers);
        final URI result_URI = restTemplate.postForLocation(POST_ADDRESS + "/type1_", httpEntity, Type1_.class);
        System.out.println("result_URI = " + result_URI);
    }
}

Потребительский бегун

public class HttpMethodPostConsumerTest {

    /*HttpClientErrorException: 415 null*/
    @Test
    public void test_postStringAsText() {
        final String text = Randomizers.getString();
        System.out.println("text = " + text);
        postStringAsText(text);
    }

    /*HttpClientErrorException: 400 null*/
    @Test
    public void test_postStringAsJSON() {
        final String text = Randomizers.getString();
        System.out.println("text = " + text);
        postStringAsJSON(text);
    }

    @Test
    public void test_postType1_() {
        final Type1_ type1_ = ModelFactory.getType1_();
        System.out.println("[Consumer] type1_ = " + type1_);
        postType1_(type1_);
    }

}

Процедура тестирования

  1. Сервер запускается первым (http://localhost:55055/)
  2. Подождите, пока сервер не заработает.
  3. Запуск test_postType1_() будет работать как положено.
  4. Выполнить test_postStringAsText() Приведет к ошибке на стороне клиента / потребителя

org.springframework.web.client.HttpClientErrorException: 415 пусто

в org.springframework.web.client.DefaultResponseErrorHandler.handleError (DefaultResponseErrorHandler.java:94) в org.springframework.web.client.DefaultResponseErrorHandler.handleError (DefaultResponseErrorHandler.java:79) в org.springframework.web.client.ResponseErrorHandler.handleError (ResponseErrorHandler.java:63) в org.springframework.web.client.RestTemplate.handleResponse (RestTemplate.java:775) в org.springframework.web.client.RestTemplate.doExecute (RestTemplate.java:728) в org.springframework.web.client.RestTemplate.execute (RestTemplate.java:684) в org.springframework.web.client.RestTemplate.postForLocation (RestTemplate.java:405) в personal.learn.java.spring_rest.rest_general.non_automated.consumers.HttpMethodPostConsumer.postStringAsText (HttpMethodPostConsumer.java:21) в personal.learn.java.spring_rest.rest_general.non_automated.consumers.HttpMethodPostConsumerTest.test_postStringAsText (HttpMethodPostConsumerTest.java:17)

  1. Запуск test_postStringAsJSON() приведет к ошибкам
    • Ошибка на стороне клиента / потребителя

org.springframework.web.client.HttpClientErrorException: 400 null

в org.springframework.web.client.DefaultResponseErrorHandler.handleError (DefaultResponseErrorHandler.java:94) в org.springframework.web.client.DefaultResponseErrorHandler.handleError (DefaultResponseErrorHandler.java:79) в org.springframework.web.client.ResponseErrorHandler.handleError (ResponseErrorHandler.java:63) в org.springframework.web.client.RestTemplate.handleResponse (RestTemplate.java:775) в org.springframework.web.client.RestTemplate.doExecute (RestTemplate.java:728) в org.springframework.web.client.RestTemplate.execute (RestTemplate.java:684) в org.springframework.web.client.RestTemplate.postForLocation (RestTemplate.java:405) в personal.learn.java.spring_rest.rest_general.non_automated.consumers.HttpMethodPostConsumer.postStringAsJSON (HttpMethodPostConsumer.java:31) в personal.learn.java.spring_rest.rest_general.non_automated.consumers.HttpMethodPostConsumerTest.test_postStringAsJSON (HttpMethodPostConsumerTest.java:25)

Ошибка на стороне сервера (в консоли)

02-May-2018 17: 25: 45.469 ПРЕДУПРЕЖДЕНИЕ [http-nio-55055-exec-2] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotReadable Не удалось прочитать сообщение HTTP: org.springframework.http.converter.HttpMessageNotReadableException: Ошибка синтаксического анализа JSON: нераспознанный токен IAtQDIxTCh: ожидалось 'null', 'true', 'false' или NaN; вложенное исключение com.fasterxml.jackson.core.JsonParseException: нераспознанный токен 'IAtQDIxTCh': ожидал 'null', 'true', 'false' или NaN в [Источник: (PushbackInputStream); строка: 1, столбец: 21]

Ошибка на стороне сервера (в Tomcat Catalina Log)

02-мая-2018 17: 25: 45.469 ПРЕДУПРЕЖДЕНИЕ [http-nio-55055-exec-2] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotReadable Не удалось прочитать сообщение HTTP: org.springframework.http.converter.HttpMessageNotReadableException: Ошибка синтаксического анализа JSON: нераспознанный токен IAtQDIxTCh: ожидалось 'null', 'true', 'false' или NaN; вложенное исключениеcom.fasterxml.jackson.core.JsonParseException: нераспознанный токен 'IAtQDIxTCh': ожидал 'null', 'true', 'false' или NaN в [Источник: (PushbackInputStream); строка: 1, столбец: 21]

1 Ответ

0 голосов
/ 02 мая 2018

Если вы хотите отправить POST на ваш сервер с помощью @RequestBody, необходимо отправить объект на ваш контроллер.

Создайте класс DTO с параметром String:

public class ExampleDTO {

 private String stringExample;

  public String getStringExample() {
    return stringExample;
  }

  public void setStringExample(String stringExample) {
    this.stringExample= stringExample;
  }

}

Ваш контроллер:

@RequestMapping(method = RequestMethod.POST, value = "/string_as_text")
public ResponseEntity<Void> getStringAsText(@RequestBody ExampleDTO exampleDTO) {
    System.out.println("[Server] text = " + exampleDTO.getStringExample());
    return new ResponseEntity<Void>(HttpStatus.OK);
}

Потребитель

ExampleDTO param = new ExampleDTO();
param.setStringExample("text")
...