Android:当网络连接发生变化时,DNS Java SRV查找失败

时间:2017-02-24 17:16:57

标签: java android dns

祝大家周五愉快!

我的Android应用程序依赖DNS Java(http://www.dnsjava.org/doc/)来执行SRV查找。我们刚刚发现,如果网络连接发生变化(从LTE切换到WiFi或反之亦然),那么从那时开始的每次查找都将永久超时,无论是否在新网络上再次建立互联网连接。有时这可以通过切换回旧网络来解决,但如果更改次数太多,则无法恢复。这是我们在下面使用的代码。

如果我能提供任何其他详细信息,请告诉我。非常感谢帮助!

private static class ConfigUpdater extends AsyncTask<Void, Void, JsonConfig> {
    private static final String SRV_RUE_CONFIG_PREFIX = "_rueconfig._tls.";
    ConfigListener listener;
    String request_url;
    String query_url;
    String username, password;
    String errorMsg;

    public ConfigUpdater(String url, String username, String password, ConfigListener listener) {
        this.username = username;
        this.password = password;
        this.listener = listener;
        query_url = SRV_RUE_CONFIG_PREFIX + url;
        errorMsg = "Failed to Login";
        org.xbill.DNS.ResolverConfig.refresh();
    }

    @Override
    protected JsonConfig doInBackground(Void... params) {
        Record[] records;// = new Record[0];
        try {
            Lookup configLookup = new Lookup(query_url, Type.SRV);
            configLookup.setCache(null);
            records = configLookup.run();
        } catch (TextParseException e) {
            e.printStackTrace();
            return null;
        }
        if(records != null && records.length > 0) {
            for (Record record : records) {
                SRVRecord srv = (SRVRecord) record;
                String hostname = srv.getTarget().toString().replaceFirst("\\.$", "");
                request_url = "https://" + hostname + "/config/v1/config.json";
                Log.d("Auto Config request_url: "+request_url);
            }

            try {
                String reponse_str = getFromHttpURLConnection();
                Log.d("Auto Config JSON: "+reponse_str);
                return parseJson(username, reponse_str, request_url);
            } catch (Throwable e){
                Log.d("Issue parsing json");
                e.printStackTrace();
            }
        }
        return null;
    }

1 个答案:

答案 0 :(得分:1)

对于任何可能在网络切换后遇到SRV查找失败的人,我似乎发现了问题。问题是Resolver对象上的Lookup属性似乎缓存了网络配置。如果要确保查找始终具有最新的网络配置,只需重新初始化新的Resolver即可。通过以下修改,我无法重现任何初始测试用例。

Record[] records = null;// = new Record[0];
        try {
            Lookup configLookup = new Lookup(query_url, Type.SRV);
            configLookup.setResolver(new ExtendedResolver()); /** FIX **/
            records = configLookup.run();
        } catch (TextParseException e) {
            e.printStackTrace();
            return null;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }