Alv*_*aro 1 java restlet restlet-2.0
我正在尝试使用Restlet 框架获取 POST 发送的参数,但找不到方法。
这是我使用 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);
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能从POST中获取数据?
更新尝试此操作后
仍然无法获取 415 Unsupported Media Type:
@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);
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,我将使用cURL通过 PHP 发出 POST 请求。
更新 2
通过删除,("json")我不再收到错误消息,但name变量为空。
更新 3
这是我正在使用的 PHP 代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
你可以做这样的事情
@Post("json")
public void someMethod(Representation rep){...}
Run Code Online (Sandbox Code Playgroud)
您可以将 json 替换为您可以处理的内容类型。
如果帖子来自简单的 html 表单,那么您可以从表示中获取 Form 对象并从中提取参数。
@Post
public void someMethod(Representation entity){
final Form form = new Form(entity);
String name = form.getFirstValue("name"));
}
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以从查询字符串构造 Form 对象。