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

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


当前回答

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

其他回答

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

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

你也可以检查具有完整客户端功能的Restlet,它比httppurlconnection或Apache HTTP Client(我们可以作为连接器使用)等底层库更面向REST。

最好的问候, 杰罗姆Louvel

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

我大部分时间都使用RestAssured来解析rest服务响应和测试服务。除了Rest Assured之外,我还使用下面的库来与Resful服务进行通信。

a. Jersey Rest客户端

b. Spring RestTemplate

c. Apache HTTP Client