美文网首页
url.openStream()连接超时设置

url.openStream()连接超时设置

作者: JiangCheng97 | 来源:发表于2019-06-04 16:09 被阅读0次

    第一种情况 会出现超时连接时间很长

    URL.openStream()可能会出现连接超时的情况,导致读取时间很长,三四分钟的样子

    URL url2g = new URL(url_2g);
    BufferedReader reader2g = null;
    try {
        reader2g = new BufferedReader(new InputStreamReader(url2g.openStream(), "UTF-8"));
    } catch (IOException e) {
        logger.error("调用moji接口失败", e);
    }
    

    第二种情况 通过设置连接超时时间

    先使用URL的openConnection方法获得一个HttpUrlConnection对象,然后该对象有setConnectTimeout和setReadTimeout两个方法,分别设置两种超时,设置完之后再调用该connection的getInputStream获得流即可。其实url的openStream就是把openConnection和getInputStream连起来调用了。

    String url_2g = WeatherUtil.getUrl(lon_2g, lat_2g);
    URL url2g = null;
    HttpURLConnection urlCon2g = null;
    try {
        url2g = new URL(url_2g);
        //设置连接超时的时间
        urlCon2g = (HttpURLConnection) url2g.openConnection();
        urlCon2g.setConnectTimeout(1000);
        urlCon2g.setReadTimeout(1000);
    } catch (Exception e) {
        logger.error("URL格式错误", e);
    }
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader2g = null;
    try {
        inputStream = urlCon2g.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        reader2g = new BufferedReader(inputStreamReader);
    } catch (IOException e) {
        logger.error(storeLocationVO.getStoreCode() + ",调用天气接口失败", e);
    }
    

    相关文章

      网友评论

          本文标题:url.openStream()连接超时设置

          本文链接:https://www.haomeiwen.com/subject/vecrxctx.html