我已经创建了一个简单的Jersey客户端,并成功地使用有效负载执行了POST请求。但现在它正在等待来自http端点的响应:
public void callEndpoint(String endpoint, String payload) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(getBaseURI(endpoint));
log.debug("Sending payload [" + payload + "] to URL - [" + getBaseURI(endpoint) + "]");
// POST method - Is this blocking?
// Is it possible to not wait for response here
ClientResponse response = webResource.accept("application/json")
.type("application/json")
.post(ClientResponse.class, payload);
if (response.getStatus() != 200) {
log.error("The endpoint [" + getBaseURI(endpoint) + "] returned a non 200 status code [" + response.getStatus() + "] ");
}
} catch (Exception e) {
log.error("The endpoint for " + endpoint + " - " + getBaseURI(endpoint) + " is not reachable. This is the exception - " + e);
}
}
private URI getBaseURI(String endpoint) {
// Get this URI from config
String URL = "http://www.somewhere.com/v2/" + endpoint;
return UriBuilder.fromUri(URL).build();
}
问题:代码是否可以不等待响应?
我正在阅读Jersey客户端文档,想知道我的代码是否有可能不等待响应?我看到我们只能在读取响应后关闭连接,但这对我的情况没有用。我想在将有效载荷发送到终端点后立即关闭连接。
我只需要启动并忘记POST请求,因为我不关心响应。这是因为处理在该终点需要很长时间,而我不希望线程等待处理。
另外,是否可能等待某些请求的响应,但不是所有请求?在客户端中是否可以设置参数以使其等待/不等待?我仍在阅读Java文档,所以这可能是一个非常简单的设置,但我现在还没有找到,所以在这里问一下。谢谢!
[更新]
我使用以下代码使其工作,但当我运行示例Java代码时,它立即打印开始和结束,但程序仍然运行一段时间,然后退出。我猜它正在等待Future响应,所以是否可能使我的脚本不等待它? 代码如下:
public static void callEndpoint(String endpoint, String payload) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
AsyncWebResource webResource = client.asyncResource(getBaseURI(endpoint));
// POST method
System.out.println("start");
Future<ClientResponse> resp = webResource.accept("application/json")
.type("application/json")
.post(ClientResponse.class, payload);
// This line makes the code wait for output
//System.out.println(resp.get());
} catch (Exception e) {
System.out.println ("The endpoint for " + endpoint + " - " + getBaseURI(endpoint) + " is not reachable. This is the exception - " + e);
}
System.out.println("done");
}