2013-10-23 5 views

答えて

51

以下のコードはジャージー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(); 
    } 
} 
+2

私はこれが機能することを疑います。 .property(...)はクライアントインスタンス(ビルダーパターン)を返します。 .target()を呼び出すときは、設定は使用されません。 – mkuff

+4

実際に動作します。ビルダー・パターンは、別のインスタンスを作成する必要があるとは言いません。ソースコードを見るだけで、戻り値は実際のクライアントです(後続の呼び出しを簡単に行うためです)。 –

20

また、リクエストごとにタイムアウトを指定することがあります。

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(); 
    } 
} 
関連する問題