Java 对Restlet服务的POST请求不支持的媒体类型(415)
IJava 对Restlet服务的POST请求不支持的媒体类型(415),java,http,restlet,media-type,Java,Http,Restlet,Media Type,IPOST到一个端点,如下所示: 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 or
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方法的输入参数传递不会使其接受appision/json
。Restlet有几种指定接受媒体类型的方法。您可以在注释中指定它,如下所示:
@Post("json")
public Representation testPost(Representation autoStackRep)
如果只提供了一个扩展,则该扩展同时适用于请求和响应实体。如果提供了两个扩展,用冒号分隔,那么第一个扩展用于请求实体,第二个扩展用于响应实体。请注意,参数类型现在是表示法
。您可以使用Representation.getText()
方法来检索响应实体的内容。还可以将POJO指定为参数类型:
@Post("json")
public MyOutputBean accept(MyInputBean input)
在这种情况下,您需要Jackson扩展能够将JSON映射到POJO,反之亦然。只需确保org.restlet.ext.jackson.jar位于类路径中。当使用POJO作为参数时,您可以省略媒体类型声明,在这种情况下,Restlet将尝试将所有可用的转换器应用于输入流,以将其映射到您的POJO。请指定包含
@Post
(非@Post
)注释的库。这是AndroidAnnotations(到目前为止我找到的最接近的一个)?谢谢@fori1ton。我已经编辑了我的问题。它的形式是restlet。