最近在做WebService时,由于要返回结果给调用接口的商户,所以用HttpURLConnection来连接商户提供的返回地址,再将结果信息送到此地址上去,在这个过程中,如果商户提供的地址是IP地址的话,就不会有问题,但有时候商户提供的是域名的地址,却是报出了:Connection refused 异常。 我又将代码在自己的机器上测试了一下,发现在自己的windows下,连接域名是没问题的!?一放到服务器上(Linux)就会报异常!下面是简化代码:
如果test_url是用IP地址的,没问题,如果是域名的,那就会在connect.getOutputStream().write()这句时报异常
查资料后得到一种说法:
在Java编程使用HttpClient的过程中,因为jre默认会对域名进行缓存以提升域名解析效率,但是目前国内的很多连锁店或Web程序用户由于经济的原因,采用了ADSL + 动态域名解析(如花生壳)的方式来进行网络程序访问,ISP为ADSL提供的ip地址一般都会定期(广东为2天一次)强制修改,这样,就会HttpClient使用中出现故障。
针对这个问题,可以通过修改jdk\jre\lib\java.security 文件来得以解决。具体的修改内容如下:
# NOTE: setting this to anything other than the default value can have
# serious security implications. Do not set it unless
# you are sure you are not exposed to DNS spoofing attack.
#
networkaddress.cache.ttl=0
# The Java-level namelookup cache policy for failed lookups:
#
# any negative value: cache forever
# any positive value: the number of seconds to cache negative lookup results
# zero: do not cache
#
# In some Microsoft Windows networking environments that employ
# the WINS name service in addition to DNS, name service lookups
# that fail may take a noticeably long time to return (approx. 5 seconds).
# For this reason the default caching policy is to maintain these
# results for 10 seconds.
按这种方法修改后,没有得到解决
- URL url = new URL(test_url);
- HttpURLConnection connect = (HttpURLConnection) url.openConnection();
- connect.setReadTimeout(30000);
- connect.setConnectTimeout(10000);
- connect.setRequestMethod("POST");
- connect.setDoInput(true);
- connect.setDoOutput(true);
- connect.getOutputStream().write(htask.getParams().getBytes("GBK"));
- connect.getOutputStream().flush();
- connect.getOutputStream().close();
- byte[] bts = new byte[250];
- connect.getInputStream().read(bts);
如果test_url是用IP地址的,没问题,如果是域名的,那就会在connect.getOutputStream().write()这句时报异常
查资料后得到一种说法:
在Java编程使用HttpClient的过程中,因为jre默认会对域名进行缓存以提升域名解析效率,但是目前国内的很多连锁店或Web程序用户由于经济的原因,采用了ADSL + 动态域名解析(如花生壳)的方式来进行网络程序访问,ISP为ADSL提供的ip地址一般都会定期(广东为2天一次)强制修改,这样,就会HttpClient使用中出现故障。
针对这个问题,可以通过修改jdk\jre\lib\java.security 文件来得以解决。具体的修改内容如下:
# NOTE: setting this to anything other than the default value can have
# serious security implications. Do not set it unless
# you are sure you are not exposed to DNS spoofing attack.
#
networkaddress.cache.ttl=0
# The Java-level namelookup cache policy for failed lookups:
#
# any negative value: cache forever
# any positive value: the number of seconds to cache negative lookup results
# zero: do not cache
#
# In some Microsoft Windows networking environments that employ
# the WINS name service in addition to DNS, name service lookups
# that fail may take a noticeably long time to return (approx. 5 seconds).
# For this reason the default caching policy is to maintain these
# results for 10 seconds.
按这种方法修改后,没有得到解决
各位高手看看是不是什么其它原因?有什么其它解决办法?
最简单做法自己连接DNS服务器查域名对应的ip