gpt4 book ai didi

java - 一个接受 JSON 对象的简单 JaxWS Rest

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:24 25 4
gpt4 key购买 nike

我正在尝试用 Java 开发一个接受通用 JsonObject(我使用 JSON Simple 1.1.1)的 Rest WebService(我使用 RestEasy)。

到目前为止我做了什么:

@Path("/message")
public class TestRestService {
@POST
@Path("/{param}")
@Consumes("application/json")
public Response printMessage(JSONObject inputJsonObj) {

String result = "Restful example : " + inputJsonObj;
System.out.println(result);
return Response.status(200).entity(result).build();
}
}

这是我的客户:

  public static void main(String[] args) {

try {

URL url = new URL("http://localhost:8080/myProject/rest/message/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");

String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) { }
catch (IOException e) { }
}

不幸的是,我收到了 405 错误,这意味着我认为的路径不存在......

有人可以帮我吗?

谢谢!

最佳答案

您似乎缺少路径的/{param} 部分。现在,您在/message 的部分之后没有任何内容,但您的网络服务器找不到仅接受/message 传递的方法。由于您没有尝试在方法中使用/{param} 我建议您从方法中删除 @Path-Annotation 。这是可能的,因为框架将尝试在下一个级别(这里是您的类级别,这将是您的/message 路径)上使用 @Path 注释,并将 HTTP 方法注释到您的方法。如果/{param} 应该是可选参数,我建议在方法头中使用 @QueryParameter 注释。有关此注释的更多信息,您应该阅读 javax.ws.rs 框架的文档。
亲切的问候

关于java - 一个接受 JSON 对象的简单 JaxWS Rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31289889/

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