【发布时间】:2015-11-08 09:14:13
【问题描述】:
此示例适用于 URL 编码的 GET! 我尝试使用不起作用的 JSON POST 来增强它。有人可以帮助我使用 JSON POST、DELETE 和 JSON PUT 以及 cmets 中的一些随附 curl 命令来演示这些命令吗?
/*
* Begin commands to execute this file using Groovy with bash
* spring run app.groovy &
* sleep 10
* curl -i -H "Accept: application/json" http://localhost:8080/greeting?name=siegfried -X GET
* End commands to execute this file using Groovy with bash
*
*
* $Log$
*
*/
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
public class Greeting {
public final long id;
public final String content;
public Greeting(){ this(0,"") }
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
}
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
"Hello World! " + new java.util.Date()
}
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
// {"id":1,"content":"Hello, siegfried!"}
//@RequestMapping(value="/g2", method=RequestMethod.GET) public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format("Hello2, %s!", name)); }
//@RequestMapping(value="/g3", method=RequestMethod.POST, headers = "Content-Type=application/json") public Greeting greeting(@RequestBody Greeting g) { return new Greeting(counter.incrementAndGet(), String.format("Hello2, %s!", g.content)); }
//{"timestamp":1439600325530,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/x-www-form-urlencoded' not supported","path":"/g3"}
}
【问题讨论】:
-
您是否尝试过使用
@Post(以及您的@RequestMapping注释)来注释您的方法?
标签: json rest groovy spring-boot