I'm tring to get the parameters sent by POST using the Restlet framework but I can't find the way.
Here's what I have working with GET:
@Get
public StringRepresentation represent() {
String search = getQuery().getValues("search");
String folder = getQuery().getValues("folder");
LinkedHashMap<String, String> list = search(search, folder);
return new StringRepresentation(JSONObject.toJSONString(list), MediaType.APPLICATION_JSON);
}
What should I do to get the data from POST?
Update
Still having troubles getting the 415 Unsupported Media Type
after trying this:
@Post("json")
public StringRepresentation represent(Representation entity) {
final Form form = new Form(entity);
String name = form.getFirstValue("search");
return new StringRepresentation(name, MediaType.APPLICATION_JSON);
}
For more information, I'm making the POST request through PHP by using cURL.
Update 2
By removing the ("json")
I don't get the error message anymore but the name
variable is empty.
Update 3
This is the PHP code I'm using:
public function restful(){
$result = $this->callAPI('POST', 'http://localhost:8182/xxxx', array('search'=> 'demo', 'folder' => 'xxxxxx'));
print_r($result);
die();
}
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
public function callAPI($method, $url, $data = false){
$curl = curl_init($url);
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data){
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
return $curl_response;
}
You can do something like this
@Post("json")
public void someMethod(Representation rep){...}
You can substitute json for the content type you can handle.
If the post is from a simple html form then you can get the Form object from the representation and extract the parameters from that.
@Post
public void someMethod(Representation entity){
final Form form = new Form(entity);
String name = form.getFirstValue("name"));
}
Note you can also construct Form objects from query strings.