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

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


当前回答

试着看看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

干杯!

其他回答

试着看看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

干杯!

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

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

我目前正在使用https://github.com/kevinsawicki/http-request,我喜欢他们的简单性和展示示例的方式,但当我阅读时,我主要是被卖了:

依赖关系是什么? 一个也没有。这个库的目标是成为带有一些内部静态类的单个类。测试项目确实需要Jetty,以便根据实际的HTTP服务器实现测试请求。

这解决了Java 1.6项目中的一些问题。至于把json解码成对象,gson是无敌的:)

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

最好的问候, 杰罗姆Louvel