gpt4 book ai didi

json - Jersey Rest Client 是否比 HttpClient 更适合调用 Restful 服务?

转载 作者:行者123 更新时间:2023-12-01 08:09:33 26 4
gpt4 key购买 nike

我需要调用将返回 json 响应的 resful api。我正在考虑使用 jersey 客户端 api,但不确定它是否比直接使用 HttpClient 然后使用 GSON 将响应转换为 Java 对象更好。

最佳答案

从编码效率的角度来看,Jersey 客户端远远优于 HttpClient。考虑:

// Jersey client
WebResource resource = Client.create().resource("http://foo.com")
resource.path("widgets").entity(someWidget).type(APPLICATION_JSON).post();
Wodget wodget = resource.path("widgets/wodget").accept(APPLICATION_XML).get(Wodget.class);

与:
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://foo.com/widgets");
HttpEntity someWidgetEntity = ... // something with GSON to marshal the 'someWidget'
httpPost.setEntity(someWidgetEntity);
HttpResponse response = httpclient.execute(httpPost);

HttpGet httpGet = new HttpGet("http://foo.com/widgets/wodget");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
... // something with GSON to read in the wodget
}

添加一个事实,即 Jersey 客户端可以在幕后使用 HttpClient 进行 HTTP 交互,您将获得两全其美:简化的界面以及广泛使用的多功能 HTTP 客户端库的强大功能。

注意:以上代码完全未经测试,但形状大致准确。

关于json - Jersey Rest Client 是否比 HttpClient 更适合调用 Restful 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15214252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com