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

时间:2015-07-08 10:24:23

标签: java json rest

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

到目前为止我做了什么:

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

有人能帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

相关问题