通过JSR 311及其实现,我们拥有了一个强大的标准,可以通过REST公开Java对象。然而,在客户端方面,似乎缺少类似于SOAP的Apache Axis的东西 - 一些隐藏Web服务并将数据透明地编组回Java对象的东西。
您如何创建Java RESTful客户端?使用HTTPConnection和手动解析结果吗?还是使用专门的客户端,例如Jersey或Apache CXF?
通过JSR 311及其实现,我们拥有了一个强大的标准,可以通过REST公开Java对象。然而,在客户端方面,似乎缺少类似于SOAP的Apache Axis的东西 - 一些隐藏Web服务并将数据透明地编组回Java对象的东西。
您如何创建Java RESTful客户端?使用HTTPConnection和手动解析结果吗?还是使用专门的客户端,例如Jersey或Apache CXF?
这是一个老问题(2008),因此现在比那时有更多的选择:
更新(2020年仍然活跃的项目):
在选择 HTTP/REST 客户端时,请注意检查您的框架堆栈正在使用哪个HTTP客户端以及它如何处理线程,如果可能,请使用相同的客户端。例如,如果您正在使用 Vert.x 或 Play 等框架,则可能要尝试使用其后端客户端来参与框架提供的任何总线或反应堆循环...否则,请准备好可能遇到有趣的线程问题。
例如:
clientConfig = new DefaultClientConfig();
client = Client.create(clientConfig);
resource = client.resource("http://localhost:8080");
// let's get the XML as a String
String text = resource("foo").accept("application/xml").get(String.class);
顺便说一下,我希望未来的JAX-RS版本能够添加一个类似Jersey中客户端API的好用的客户端API。
您可以使用标准的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);
更多信息请参见:
如果你只想调用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,它具有完整的客户端能力,更加面向 REST,比底层库(如 HttpURLConnection 或 Apache HTTP Client)更为适用(我们可以将其作为连接器)。
敬礼, Jerome Louvel
试试来自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
OkHttp是一个轻量而强大的HTTP客户端库,与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();
}
Retrofit: http://square.github.io/retrofit/
public interface GitHubService {
@GET("/users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}