Programing

JSON에서 RestTemplate을 통한 POST 요청

lottogame 2020. 7. 22. 21:35
반응형

JSON에서 RestTemplate을 통한 POST 요청


내 문제를 해결하는 방법에 대한 예를 찾지 못 했으므로 도움을 요청하고 싶습니다. JSON에서 RestTemplate 객체를 사용하여 POST 요청을 보낼 수는 없습니다.

내가 얻을 때마다 :

org.springframework.web.client.HttpClientErrorException : 415 지원되지 않는 미디어 유형

이런 식으로 RestTemplate을 사용합니다.

...
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
...
Payment payment= new Payment("Aa4bhs");
Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment", payment, Payment.class);

내 잘못은 무엇입니까?


이 기술은 저에게 효과적이었습니다.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);

이게 도움이 되길 바란다


REST 엔드 포인트를 디버깅하려고 할 때이 문제를 겪었습니다. 다음은 Spring의 RestTemplate 클래스를 사용하여 내가 사용한 POST 요청을 만드는 기본 예입니다. 다른 버전의 코드를 함께 사용하여 작업 버전을 얻는 데 시간이 오래 걸렸습니다.

RestTemplate restTemplate = new RestTemplate();

String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);

내 나머지 엔드 포인트가 필드 이름 주위에 필요한 큰 따옴표를 사용했기 때문에 requestJson String에서 큰 따옴표를 이스케이프 처리 한 이유입니다.


JSONObjects와 함께 나머지 템플릿을 다음과 같이 사용했습니다.

// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);

// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);

// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
  .exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
  JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
  // nono... bad credentials
}

여기에 지정된대로 messageConverterfor 를 추가해야한다고 생각합니다.MappingJacksonHttpMessageConverter


Spring 3.0을 사용하는 경우 org.springframework.web.client.HttpClientErrorException 을 피하는 쉬운 방법 : 415 지원되지 않는 미디어 유형 예외는 클래스 경로에 jackson jar 파일을 포함시키고 mvc:annotation-drivenconfig 요소를 사용하는 것 입니다. 여기에 지정된대로 .

mvc-ajax 앱이 특별한 구성없이 작동 하는 이유를 알아 내려고 노력 했습니다 MappingJacksonHttpMessageConverter. 위의 기사를 자세히 읽으면 위의 내용을 자세히 볼 수 있습니다.

Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.


The "415 Unsupported Media Type" error is telling you that the server will not accept your POST request. Your request is absolutely fine, it's the server that's mis-configured.

MappingJacksonHttpMessageConverter will automatically set the request content-type header to application/json, and my guess is that your server is rejecting that. You haven't told us anything about your server setup, though, so I can't really advise you on that.


I'm doing in this way and it works .

HttpHeaders headers = createHttpHeaders(map);
public HttpHeaders createHttpHeaders(Map<String, String> map)
{   
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    for (Entry<String, String> entry : map.entrySet()) {
        headers.add(entry.getKey(),entry.getValue());
    }
    return headers;
}

// Pass headers here

 String requestJson = "{ // Construct your JSON here }";
logger.info("Request JSON ="+requestJson);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
logger.info("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
logger.info("Response ="+response.getBody());

Hope this helps


I was getting this problem and I'm using Spring's RestTemplate on the client and Spring Web on the server. Both APIs have very poor error reporting, making them extremely difficult to develop with.

After many hours of trying all sorts of experiments I figured out that the issue was being caused by passing in a null reference for the POST body instead of the expected List. I presume that RestTemplate cannot determine the content-type from a null object, but doesn't complain about it. After adding the correct headers, I started getting a different server-side exception in Spring before entering my service method.

The fix was to pass in an empty List from the client instead of null. No headers are required since the default content-type is used for non-null objects.


This code is working for me;

RestTemplate restTemplate = new RestTemplate();
Payment payment = new Payment("Aa4bhs");
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("payment", payment);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headerObject);

Payment res = restTemplate.postForObject(url, httpEntity, Payment.class);

If you dont want to process response

private RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(serviceURL, request, Void.class);

If you need response to process

String result = restTemplate.postForObject(url, entity, String.class);

For me error occurred with this setup:

AndroidAnnotations Spring Android RestTemplate Module and ...

GsonHttpMessageConverter

Android annotations has some problems with this converted to generate POST request without parameter. Simply parameter new Object() solved it for me.


Why work harder than you have to? postForEntity accepts a simple Map object as input. The following works fine for me while writing tests for a given REST endpoint in Spring. I believe it's the simplest possible way of making a JSON POST request in Spring:

@Test
public void shouldLoginSuccessfully() {
  // 'restTemplate' below has been @Autowired prior to this
  Map map = new HashMap<String, String>();
  map.put("username", "bob123");
  map.put("password", "myP@ssw0rd");
  ResponseEntity<Void> resp = restTemplate.postForEntity(
      "http://localhost:8000/login",
      map,
      Void.class);
  assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}

참고URL : https://stackoverflow.com/questions/4075991/post-request-via-resttemplate-in-json

반응형