【问题标题】:A simple JaxWS Rest that accept JSON Object一个接受 JSON 对象的简单 JaxWS Rest
【发布时间】:2015-07-08 10:24:22
【问题描述】:

我正在尝试用 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 错误,这意味着我认为的路径不存在...

谁能帮帮我?

谢谢!

【问题讨论】:

  • 响应代码 405 是 方法不允许。您是否缺少客户端 URL 上的 {param}

标签: java json rest


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2016-12-28
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2015-03-22
    • 2016-05-27
    相关资源
    最近更新 更多