gpt4 book ai didi

java - ReSTLet 服务的 POST 请求不支持媒体类型 (415)

转载 作者:可可西里 更新时间:2023-11-01 17:36:30 24 4
gpt4 key购买 nike

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。

关于java - ReSTLet 服务的 POST 请求不支持媒体类型 (415),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com