通过JSON中的RestTemplate发出POST请求

Joh*_*y B 117 java rest spring json resttemplate

我没有找到任何解决问题的例子,所以我想请你帮忙.我不能简单地使用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);
Run Code Online (Sandbox Code Playgroud)

我的错是什么?

小智 152

这项技术对我有用:

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

HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

  • 方法`.put()`是`void`! (20认同)
  • 使用`postForEntity(url,entity,String.class)`代替`put(url,entity)` (4认同)
  • 请说明哪一行应该返回http请求的结果 (3认同)

Mor*_*yon 90

我在尝试调试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);
Run Code Online (Sandbox Code Playgroud)

我的休息端点使用特定的JSON解析器在字段名称周围使用所需的双引号,这就是为什么我在requestJson String中转义了双引号.


Mik*_*stö 73

我一直在使用JSONObjects的rest模板如下:

// 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
}
Run Code Online (Sandbox Code Playgroud)


Rag*_*ram 13

正如这里指出的,我想你需要添加一个messageConverterfor MappingJacksonHttpMessageConverter


Mik*_*e G 9

如果您使用的是Spring 3.0,那么避免org.springframework.web.client.HttpClientErrorException:415不支持的媒体类型异常的简单方法是在您的类路径中包含jackson jar文件,并使用mvc:annotation-drivenconfig元素.如此处所述.

我正在拉我的头发试图弄清楚为什么mvc-ajax应用程序工作没有任何特殊的配置MappingJacksonHttpMessageConverter.如果你仔细阅读我上面链接的文章:

在封面下,Spring MVC委托HttpMessageConverter执行序列化.在这种情况下,Spring MVC调用基于Jackson JSON处理器构建的MappingJacksonHttpMessageConverter.当您使用mvc:annotation-driven配置元素并且类路径中存在Jackson时,将自动启用此实现.


ska*_*man 7

"415 Unsupported Media Type"错误告诉您服务器不接受您的POST请求.您的请求绝对正常,这是错误配置的服务器.

MappingJacksonHttpMessageConverter将自动设置请求内容类型标头application/json,我的猜测是你的服务器拒绝.但是,您没有告诉我们有关您的服务器设置的任何信息,因此我无法真正为您提供建议.


Yak*_*oob 6

我是用这种方式做的,而且有效。

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;
}
Run Code Online (Sandbox Code Playgroud)

//在此处传递标题

 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());
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助


eri*_*egz 6

为什么要比你应该做的更努力地工作?postForEntity接受一个简单的Map对象作为输入。在 Spring 中为给定 REST 端点编写测试时,以下内容对我来说效果很好。我相信这是在 Spring 中发出 JSON POST 请求的最简单的方法:

@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);
}
Run Code Online (Sandbox Code Playgroud)