通过JSR 311及其实现,我们有了一个通过REST公开Java对象的强大标准。然而,在客户端,似乎缺少了一些类似于Apache Axis for SOAP的东西——隐藏web服务并将数据透明地封送回Java对象的东西。

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


当前回答

泽西休息客户端的例子

添加依赖项:

<!-- 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>

对于GetMethod,并传递两个参数:

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));    
}

上面它返回一个列表,我们将其作为list对象接受,然后将其转换为JSONArray,然后从JSONArray转换为list。

Post请求传递JSONObject作为参数:

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 "));
}

其他回答

我写了一个库,将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);
}

泽西休息客户端的例子

添加依赖项:

<!-- 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>

对于GetMethod,并传递两个参数:

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));    
}

上面它返回一个列表,我们将其作为list对象接受,然后将其转换为JSONArray,然后从JSONArray转换为list。

Post请求传递JSONObject作为参数:

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 "));
}

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

我为XML内容编写XML SAX解析器,用于将XML解析为对象模型。我认为Axis2还公开了XML -> Model方法(Axis 1隐藏了这一部分,令人恼火)。XML生成器非常简单。

在我看来,它不需要很长时间来编码,而且非常高效。

你可以试试拉帕。让我们知道你的反馈。 并随时记录问题或预期的功能。

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