![](/img/trans.png)
[英]POST to Jersey REST service getting error 415 Unsupported Media Type
[英]Unsupported Media Type (415) for POST request to Restlet service
我POST
像以下端点:
import java.util.logging.Level;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
try {
JSONObject jsonToCallback = AcceptorManager.getJsonFromClient();
String test = jsonToCallback.getString("test");
String st2 = jsonToCallback.getString("st2");
ClientResource clientResource = new ClientResource(callback);
clientResource.setMethod(Method.POST);
Form form = new Form ();
form.add("key1", val1);
form.add("key2", "stat");
Representation representation = clientResource.post(form, MediaType.APPLICATION_JSON);
} catch (Exception e) {
//Here I get "Unsupported Media Type (415) - Unsupported Media Type"
}
这是端点:
public class test extends ServerResource{
@Post
public JSONObject testPost(JSONObject autoStackRep) throws JSONException, AcceptorException {
JSONObject json=new JSONObject();
try {
json.put("result",false);
json.put("id",1);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
如何解决此问题?
将JSONObject
传递为POST方法的输入参数不会使其接受appication/json
。 Restlet有几种指定接受的媒体类型的方法。 您可以在@Post
批注中指定它,如下所示:
@Post("json")
public Representation testPost(Representation autoStackRep)
如果仅提供一个扩展,则该扩展适用于请求和响应实体。 如果提供了两个扩展名,并用冒号分隔,则第一个扩展名用于请求实体,第二个扩展名用于响应实体。 请注意,参数类型现在为Representation
。 您可以使用Representation.getText()
方法来检索响应实体的内容。 您还可以将POJO指定为参数类型:
@Post("json")
public MyOutputBean accept(MyInputBean input)
在这种情况下,您需要Jackson扩展才能将JSON映射到POJO,反之亦然。 只要确保org.restlet.ext.jackson.jar在您的类路径中即可。 使用POJO作为参数时,您可以省略媒体类型声明,在这种情况下,Restlet将尝试将所有可用的转换器应用于输入流,以将其映射到您的POJO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.