java - 使用 Jersey 从客户端调用 RESTFul Web 服务的问题

标签 java web-services jersey

我正在尝试使用 Jersey 并遵循 this example 来学习 RESTFul Web 服务.我创建了一个示例服务,可在以下位置访问:

    http://localhost:8080/de.vogella.jersey.first/rest/hello. 

我已经创建了一个调用此服务的客户端,但是当我运行此客户端时,出现如下异常:

   GET http://localhost:8080/de.vogella.jersey.first/rest/hello 
     returned a response status of 404 Not Found Exception in thread "main"  
   com.sun.jersey.api.client.UniformInterfaceException: 
     GET http://localhost:8080/de.vogella.jersey.first/rest/hello 
       returned a response status of 404 Not Found
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507)
at de.vogella.jersey.first.client.Test.main(Test.java:23)

服务等级是

public class Hello {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }
}

客户端代码:

public class Test {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());  
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));        
    private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.first").build();
  }
} 

奇怪的是,如果我点击,我可以得到正确的结果

    http://localhost:8080/de.vogella.jersey.first/rest/hello 

来自浏览器。解决此问题的任何帮助表示赞赏。 谢谢

最佳答案

根据您在服务应用程序中的要求,您在创建类之前没有提及“路径”注释,例如:

@Path("hello")
public class Hello {

}

那只是您的服务应用程序中的问题。

关于java - 使用 Jersey 从客户端调用 RESTFul Web 服务的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13020408/

相关文章:

java - 不稳定的测试 Selenium

java - 无法运行Java命令

java - 请求参数在 Tomcat 中被丢弃

java - @Post Jersey 在带有 javax.ws.rs.POST 注释的方法中只允许有一个未注释的参数

rest - 在类级别上具有空值的 Jersey 注释 @Path 不起作用

java - 如何在 Jersey 中实现这种身份验证机制

java - 如何在Android Studio 3.3中正确实现MapQuest的API

Java Spring 工作流程

ios - swift curl ——用户帖子

java - maven-shade-plugin ConnectException : Connection refused for getting java. sun.com DTD(由 XMLAppendingTransformer 处理以构建 Apache CXF)