用于Java的REST客户端?

时间:2008-10-21 10:50:59

标签: java rest client

使用JSR 311及其实现,我们有一个强大的标准,可以通过REST公开Java对象。然而,在客户端,似乎缺少可与Apache Axis for SOAP相媲美的东西 - 隐藏Web服务并将数据透明地封送回Java对象。

如何创建Java RESTful客户端?使用HTTPConnection和手动解析结果?或专门的客户,例如Jersey或Apache CXR?

19 个答案:

答案 0 :(得分:177)

这是一个老问题(2008)所以现在有比以往更多的选择:

更新大约2014年:

该块上的新孩子提供NIO支持(虽然我不认为这确实提高了客户端的性能,例如服务器)。

2016年更新

  • OkHttp - 支持更新的HTTP协议(SPDY和HTTP2)。适用于Android。不幸的是,它没有提供真正的基于反应器循环的异步选项(参见上面的Ning和HTTP组件)。但是,如果您使用较新的HTTP2协议,则这不是问题(假设连接计数有问题)。
  • Retrofit - 将根据类似于某些Jersey和CXF扩展的接口存根自动创建客户端。使用OkHttp。
  • Apache HttpComponents 5应该具有HTTP2支持

关于选择HTTP / REST客户端的警告。确保检查您的框架堆栈用于HTTP客户端的内容,它如何进行线程化,并且如果它提供了一个,则理想情况下使用相同的客户端。也就是说,如果您使用Vert.x或Play之类的东西,您可能想尝试使用其支持客户端参与框架提供的任何总线或反应器循环......否则请为可能有趣的线程问题做好准备。

答案 1 :(得分:70)

正如我在this thread中提到的,我倾向于使用实现JAX-RS的Jersey并且附带一个不错的REST客户端。好的是,如果使用JAX-RS实现RESTful资源,那么Jersey客户端可以重用实体提供程序,例如JAXB / XML / JSON / Atom等等 - 这样您就可以在服务器端重用相同的对象了用于客户端单元测试。

例如来自here is a unit test caseApache Camel project,它从RESTful资源中查找XML有效负载(使用JAXB对象端点)。资源(uri)方法在this base class中定义,它只使用Jersey客户端API。

e.g。

    clientConfig = new DefaultClientConfig();
    client = Client.create(clientConfig);

    resource = client.resource("http://localhost:8080");
    // lets get the XML as a String
    String text = resource("foo").accept("application/xml").get(String.class);        

顺便说一下,我希望JAX-RS的未来版本能够在Jersey中添加一个不错的客户端API

答案 2 :(得分:60)

您可以使用标准Java SE API:

private void updateCustomer(Customer customer) { 
    try { 
        URL url = new URL("http://www.example.com/customers"); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
        connection.setDoOutput(true); 
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("PUT"); 
        connection.setRequestProperty("Content-Type", "application/xml"); 

        OutputStream os = connection.getOutputStream(); 
        jaxbContext.createMarshaller().marshal(customer, os); 
        os.flush(); 

        connection.getResponseCode(); 
        connection.disconnect(); 
    } catch(Exception e) { 
        throw new RuntimeException(e); 
    } 
} 

或者您可以使用JAX-RS实现(如Jersey)提供的REST客户端API。这些API更易于使用,但在类路径上需要额外的jar。

WebResource resource = client.resource("http://www.example.com/customers"); 
ClientResponse response = resource.type("application/xml");).put(ClientResponse.class, "<customer>...</customer."); 
System.out.println(response); 

有关详细信息,请参阅:

答案 3 :(得分:11)

如果您只想调用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]");

答案 4 :(得分:10)

您还可以检查具有完整客户端功能的Restlet,更多面向REST的低级库,例如HttpURLConnection或Apache HTTP Client(我们可以利用它们作为连接器)。

祝你好运, 杰罗姆·洛维尔

答案 5 :(得分:7)

您可以尝试Rapa。请告诉我们您的反馈意见。 并随时记录问题或预期功能。

答案 6 :(得分:7)

我最近在广场试过了Retrofit图书馆,很棒,你可以很容易地调用你的其他API。 基于注释的配置允许我们摆脱大量的锅炉板编码。

答案 7 :(得分:6)

我想指出另外两个选项:

答案 8 :(得分:5)

我使用Apache HTTPClient来处理所有HTTP方面。

我为XML内容编写XML SAX解析器,将XML解析为对象模型。我相信Axis2也暴露了XML - &gt;模型方法(Axis 1隐藏了这一部分)。 XML生成器非常简单。

在我看来,编码并不需要很长时间,效率很高。

答案 9 :(得分:5)

OkHttp与Retrofit结合使用时重量轻且功能强大。这适用于一般的Java使用以及Android。

OkHttp http://square.github.io/okhttp/

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

改造http://square.github.io/retrofit/

public interface GitHubService {
  @GET("/users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

答案 10 :(得分:4)

jcabi-http尝试JdkRequest(我是开发人员)。这是它的工作原理:

String body = new JdkRequest("http://www.google.com")
  .header("User-Agent", "it's me")
  .fetch()
  .body()

查看此博客文章了解更多详情:http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

答案 11 :(得分:4)

由于没有人提及,这是另一个:Feign,由Spring Cloud使用。

答案 12 :(得分:2)

有一段时间了,我一直在使用Resty

JSONResource jsonResource = new Resty().json(uri);

可以找到一些例子here

答案 13 :(得分:1)

虽然创建一个HTTP客户端很简单并且可以做出反应。但是如果你想使用一些自动生成的客户端,你可以使用WADL来描述和生成代码。

您可以使用RestDescribe生成和编译WSDL,您可以使用此生成php,ruby,python,java和C#中的客户端。它生成了干净的代码,并且在代码生成之后你必须稍微调整它,你可以找到工具here背后的良好文档和基本思想。

在wintermute上提到的有趣且有用WADL tools

答案 14 :(得分:1)

泽西休息客户的例子:
添加依赖:

         <!-- jersey -->
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.8</version>
    </dependency>
   <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.8</version>
    </dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.8</version>
</dependency>

    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

ForGetMethod并传递两个参数:

          Client client = Client.create();
           WebResource webResource1 = client
                        .resource("http://localhost:10102/NewsTickerServices/AddGroup/"
                                + userN + "/" + groupName);

                ClientResponse response1 = webResource1.get(ClientResponse.class);
                System.out.println("responser is" + response1);

GetMethod传递一个参数并获得List的响应:

       Client client = Client.create();

        WebResource webResource1 = client
                    .resource("http://localhost:10102/NewsTickerServices/GetAssignedUser/"+grpName);    
    //value changed
    String response1 = webResource1.type(MediaType.APPLICATION_JSON).get(String.class);

    List <String > Assignedlist =new ArrayList<String>();
     JSONArray jsonArr2 =new JSONArray(response1);
    for (int i =0;i<jsonArr2.length();i++){

        Assignedlist.add(jsonArr2.getString(i));    
    }

In Above It返回一个List,我们接受它作为List,然后将其转换为Json Array,然后将Json Array转换为List。

如果Post Request将Json Object作为参数传递:

   Client client = Client.create();
    WebResource webResource = client
            .resource("http://localhost:10102/NewsTickerServices/CreateJUser");
    // value added

    ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,mapper.writeValueAsString(user));

    if (response.getStatus() == 500) {

        context.addMessage(null, new FacesMessage("User already exist "));
    }

答案 15 :(得分:1)

尝试查看http-rest-client

https://github.com/g00dnatur3/http-rest-client

这是一个简单的例子:

RestClient client = RestClient.builder().build();
String geocoderUrl = "http://maps.googleapis.com/maps/api/geocode/json"
Map<String, String> params = Maps.newHashMap();
params.put("address", "beverly hills 90210");
params.put("sensor", "false");
JsonNode node = client.get(geocoderUrl, params, JsonNode.class);

库负责json序列化和绑定。

这是另一个例子,

RestClient client = RestClient.builder().build();
String url = ...
Person person = ...
Header header = client.create(url, person);
if (header != null) System.out.println("Location header is:" + header.value());

最后一个例子,

RestClient client = RestClient.builder().build();
String url = ...
Person person = client.get(url, null, Person.class); //no queryParams

干杯!

答案 16 :(得分:1)

我写了一个将java接口映射到远程JSON REST服务的库:

https://github.com/ggeorgovassilis/spring-rest-invoker

public interface BookService {
   @RequestMapping("/volumes")
   QueryResult findBooksByTitle(@RequestParam("q") String q);

   @RequestMapping("/volumes/{id}")
   Item findBookById(@PathVariable("id") String id);
}

答案 17 :(得分:0)

我大部分时间都使用RestAssured来解析其余的服务响应并测试服务。除了“确保放心”外,我还使用以下库与Resful服务进行通信。

a。 Jersey Rest Client

b。 Spring RestTemplate

c。 Apache HTTP Client

答案 18 :(得分:0)

我目前正在使用https://github.com/kevinsawicki/http-request,我喜欢它们的简单性以及示例的显示方式,但是当我阅读以下内容时,我大多被卖了:

有哪些依赖性?

没有。该库的目标是成为带有某些内部静态类的单个类。测试项目确实需要Jetty才能针对实际的HTTP服务器实现测试请求。

整理了Java 1.6项目中的一些问题。至于将json解码为对象gson则是无敌的:)