2014-01-13 66 views
3

在我的單元測試,我使用Commons的HttpClient請求不正確遠程Web站點,最大超時爲:如何在查找主機時設置套接字超時?

@Test(timeout = 10000) 
public void should_not_be_accessible_if_configuration_is_incorrect() throws Exception { 
    // use httpclient to visit an invalid remote http web site 
} 

但它可能在某些計算機拋出這樣的例外:

java.lang.Exception: test timed out after 10000 milliseconds 
at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) 
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:894) 
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1286) 
at java.net.InetAddress.getAllByName0(InetAddress.java:1239) 
at java.net.InetAddress.getAllByName(InetAddress.java:1155) 
at java.net.InetAddress.getAllByName(InetAddress.java:1091) 
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44) 
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102) 
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:314) 
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:357) 
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:218) 
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:194) 
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85) 
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) 
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186) 
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) 
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106) 
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57) 

似乎它阻止的方法:java.net.Inet4AddressImpl.lookupAllHostAddr()

我不知道是否有任何方法來設置它的最大超時?

+0

請看下面的帖子http://stackoverflow.com/questions/4969760/set-timeout-for-socket – sasankad

+1

@ sasanad號這些連接和讀取超時。這個問題是關於DNS超時的。與此問題相關的唯一答案是[我](http://stackoverflow.com/a/15519363/207421),它不提供此OP的解決方案。 – EJP

回答

4

您可以通過超時屬性來控制Java的DNS超時描述here

com.example.jndi.dns.timeout.initial 
com.example.jndi.dns.timeout.retries 
+1

做這些JNDI DNS超時值是否對非JNDI DNS行爲有任何影響,例如Java中標準URLConnection的行爲? –