Android: Retrieve JSON from service via DNS SRV lookup

Quick snippet of code for anyone in need of an SRV lookup example. If your apps retrieve data from a service and you’re hard coding a URL, DNS is a great way to make that more dynamic. DNS Java is the library being used here (http://www.dnsjava.org/doc/).

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;
    }

You may also like...

Leave a Reply