Mar*_*ijk 41 rest spring controller spring-mvc
拥有以下代码:
@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(@RequestBody String json) {
System.out.println("json = " + json); // TODO json is null... how to retrieve plain json body?
return "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)
尽管json在正文中发送,但String json参数始终为null.
请注意,我不想要自动类型转换,我只想要普通的json结果.
这例如有效:
@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(@RequestBody User user) {
return String.format("Hello %s!", user);
}
Run Code Online (Sandbox Code Playgroud)
可能我可以使用ServletRequest或InputStream作为参数来检索实际的身体,但我想知道是否有更简单的方法?
Mar*_*ijk 70
我发现的最佳方法是:
@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(HttpEntity<String> httpEntity) {
String json = httpEntity.getBody();
// json contains the plain json string
Run Code Online (Sandbox Code Playgroud)
如果还有其他选择,请告诉我.
aGO*_*aGO 14
你可以使用
@RequestBody String pBody
Jar*_*der 11
只有HttpServletRequest为我工作.HttpEntity给出了空字符串.
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(HttpServletRequest request) throws IOException {
final String json = IOUtils.toString(request.getInputStream());
System.out.println("json = " + json);
return "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)
小智 7
对我有用的最简单的方法是
@RequestMapping(value = "/greeting", method = POST, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String greetingJson(String raw) {
System.out.println("json = " + raw);
return "OK";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
55588 次 |
最近记录: |