我正在使用jersey-client 1.19。我有以下代码行可以向服务器提交请求并获得响应:

Client client = Client.create();

WebResource webResource = client.resource("http://localhost:8080/RESTfulExample/rest/json/metallica/post");
String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";

ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);

if (response.getStatus() != 201) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}


我有一个问题,当执行post方法时,如果与服务器的连接出现问题(Internet连接缓慢,它将在3分钟后响应),则代码if (response.getStatus() != 201)将继续运行或将等待执行?

最佳答案

下一行是对服务器的blocking (synchronous)调用-

ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);


这意味着该行等待服务器响应。在此行之后,程序的执行将不会继续,直到从服务器收到一些成功/错误响应。

这意味着在此行之后编写的代码-

if (response.getStatus() != 201) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}


它将等待上一行的完全执行(方法后响应)。

有关信息,Jersey还支持对服务器的non-blocking (asynchronous)调用。有关详细信息,请检查here。另外,我建议不要使用旧版本的jersey。当前版本是2.5.1,jersey 1.x and 2.x之间有很多区别

09-10 10:12
查看更多