使用apache http客户端时java.net.UnknownHostException

时间:2015-03-04 12:44:51

标签: java httpclient

我正在使用HttpClient连接到某个第三方url.Its工作正常。但有时它给出了java.net.UnknownHostException以及连接Reset Excetion。请帮助避免例外。

以下是我的代码段。

    PostMethod post = null;
 try
 {
     for(int i =0 ; i < 72 ; i++)
     {
        String url ="http://www.accuweather.com/en/in/amritsar/205593//hourly-weather-forecast/205593?hour=0";
        post = new PostMethod(url);
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=" + "UTF-8");
        post.setRequestHeader("Accept-Charset", "UTF-8");
        HttpClient httpclient = new HttpClient();
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000);
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120000);

        result = httpclient.executeMethod(post);
     }
 }
 catch(Exception e){}
 finaly
 {
     post.releaseConnection();
 }

下面是异常追踪:

java.net.UnknownHostException: www.accuweather.com
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80)
    at org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory$1.doit(ControllerThreadSocketFactory.java:91)
    at org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory$SocketTask.run(ControllerThreadSocketFactory.java:158)
    at java.lang.Thread.run(Unknown Source)

1 个答案:

答案 0 :(得分:0)

很可能,你只是有一个片状的互联网连接。我猜这是在手机上,在这种情况下,片状互联网连接是一种普遍的现实,你只需要以某种方式处理它。

处理它的最佳方法究竟是什么,取决于你的程序和背景,当然。由于您声明定期运行此方法,因此处理它的一种方法可能是简单地忽略错误(捕获异常并在发生时静默中止尝试)然后等待下一次常规运行。另一种选择可能是重复尝试一定次数。我相信还有其他可想到的方法。