我是一个初学者,我对Resteasy有点迷失
我想使用以下网址发送帖子请求:http : //myurl.com/options?value=3name=picture
String myValue = "3";
String myName = "picture";
String key = "topsecret";
Run Code Online (Sandbox Code Playgroud)
我不太确定会发生什么。我看过几个教程类(对我来说不是很清楚)以及与此类似的另一种方式
final MultivaluedMap<String, Object> queryParams = new MultivaluedMapImpl<>();
queryParams.add("value", myValue);
queryParams.add("name", myPicture);
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target(url).queryParams(queryParams);;
final Builder builder = target.request();
Run Code Online (Sandbox Code Playgroud)
我写书的时候有很多警告。这是正确的方法吗?API密钥呢?
首先,您必须检查要使用的API的文档,以了解如何将API密钥发送到服务器。 并非所有API都遵循相同的方法。
出于示例目的,假设必须在X-Api-Key标头中发送API密钥。这是非标准的,我只是为了演示如何使用客户端API而作了补充。
因此,您可以拥有以下内容:
// Create a client
Client client = ClientBuilder.newClient();
// Define a target
WebTarget target = client.target("http://myurl.com/options")
.queryParam("value", "3")
.queryParam("name", "picture");
// Perform a request to the target
Response response = target.request().header("X-Api-Key", "topsecret")
.post(Entity.text(""));
// Process the response
// This part is up to you
// Close the response
response.close();
// Close the client
client.close();
Run Code Online (Sandbox Code Playgroud)
上面的代码使用由RESTEasy实现的JAX-RS API。您最好尽量Client不要使用,ResteasyClient以确保与其他实现的可移植性。
上面的代码还假定您要在请求有效负载中发送空文本。相应地修改它。
Response包含未消耗的实体输入流的实例应关闭。对于仅处理响应头和状态代码而忽略响应实体的情况,这是典型的方案。
超出问题的范围,请记住,Client实例是管理基础客户端通信基础结构的重量级对象。因此,初始化以及Client实例的处置可能是相当昂贵的操作。
该文档建议仅创建少量Client实例,并在可能的情况下重用它们。它还指出,在处置Client实例之前必须正确关闭它们,以避免资源泄漏。
| 归档时间: |
|
| 查看次数: |
1784 次 |
| 最近记录: |