如何使用Jersey 2.x设置连接和读取超时?

在jersey1中,我们在com.sun.jersey.api.client.Client类中有一个函数setConnectTimeout 。

在泽西岛2中, javax.ws.rs.client.Client类被用在缺less这个函数的地方。

如何在jersey2.x中设置连接超时和读取超时?

下面的代码适用于泽西岛2.3.1(灵感来源于: https : //stackoverflow.com/a/19541931/1617124 )

 public static void main(String[] args) { Client client = ClientBuilder.newClient(); client.property(ClientProperties.CONNECT_TIMEOUT, 1000); client.property(ClientProperties.READ_TIMEOUT, 1000); WebTarget target = client.target("http://1.2.3.4:8080"); try { String responseMsg = target.path("application.wadl").request().get(String.class); System.out.println("responseMsg: " + responseMsg); } catch (ProcessingException pe) { pe.printStackTrace(); } } 

您也可以为每个请求指定一个超时值:

 public static void main(String[] args) { Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://1.2.3.4:8080"); // default timeout value for all requests client.property(ClientProperties.CONNECT_TIMEOUT, 1000); client.property(ClientProperties.READ_TIMEOUT, 1000); try { Invocation.Builder request = target.request(); // overriden timeout value for this request request.property(ClientProperties.CONNECT_TIMEOUT, 500); request.property(ClientProperties.READ_TIMEOUT, 500); String responseMsg = request.get(String.class); System.out.println("responseMsg: " + responseMsg); } catch (ProcessingException pe) { pe.printStackTrace(); } }