用于调用 REST 服务的 Java API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1289704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java API for invoking REST services
提问by Rich Seller
Could any one please suggest a better open source Java API for invoking REST services? Also wanted to know if Restlet API supports NTLM authentication.
有人可以建议一个更好的开源 Java API 来调用 REST 服务吗?还想知道 Restlet API 是否支持 NTLM 身份验证。
Thanks
谢谢
回答by Gandalf
It's REST - the whole point is you don't need an API per se, just HttpURLConnection. You should be able to interact with any truly RESTful service with the basic Java SDK alone. You can get fancier with Apache Commons HTTPClient - but it's not a necessity.
它是 REST - 重点是您不需要 API 本身,只需要 HttpURLConnection。您应该能够单独使用基本的 Java SDK 与任何真正的 RESTful 服务进行交互。您可以更喜欢使用 Apache Commons HTTPClient - 但这不是必需的。
回答by Rich Seller
回答by Johan
If you only wish to invoke a REST service and get the response you can try out REST Assured:
如果您只想调用 REST 服务并获得响应,您可以尝试REST Assured:
// Make a GET request to "/lotto"
String json = get("/lotto").asString()
// Parse the JSON response
List<String> winnderIds = with(json).get("lotto.winners.winnerId");
// Make a POST request to "/shopping"
String xml = post("/shopping").andReturn().body().asString()
// Parse the XML
Node category = with(xml).get("shopping.category[0]");
回答by Diego Dias
I am using resteasy as the rest frameworks and it works just fine and easy (both to rewrite and to test, same as easymock). As a sample code:
我使用resteasy作为rest框架,它工作得很好而且很容易(重写和测试,与easymock相同)。作为示例代码:
@Path("/webservice")
public class Web
{
@GET
@Path("{web}")
@ProduceMime("application/xml")
public String test(@QueryParam("param") String param, @PathParam("web") String web)
{
// code here
}
}
- @Path is your "root path" of the class (your real "root" would be configured on components.xml)
- @GET is from Rest
- ProduceMime or ConsumeMime is the mime you should consume or produce
- @QueryParam is the params of the url and @PathParam the parameters you should get
- @Path 是您的类的“根路径”(您真正的“根”将在 components.xml 上配置)
- @GET 来自 Rest
- ProduceMime 或 ConsumeMime 是您应该消费或生产的 mime
- @QueryParam 是 url 的参数,@PathParam 是你应该得到的参数
So this get will receive a call from /webservice/web?param=lalala and return a string in the application/xml format
所以这个 get 将接收来自 /webservice/web?param=lalala 的调用并返回一个 application/xml 格式的字符串

