Skip to content

Idea: Follow redirects #3

@TorstenH82

Description

@TorstenH82

To simplify the usage of the libary it should be possible to get the result after following the redirects:

Currently I need to do that:

Record record = application.getRecords().get(0);
        sSiUrl = "http://" + record.getTarget().toString();
        if (sSiUrl.endsWith(".")) sSiUrl = sSiUrl.substring(0, sSiUrl.length() - 1);

        sSiUrl += ":" + record.getPort() + "/radiodns/spi/3.1/SI.xml";

sSiUrl = getUrlAfterRedirect(sSiUrl);
private String getUrlAfterRedirect(String url) throws IOException {
    HttpURLConnection conn;

    int redirect = 0;
    while (true) {
      if (redirect > 3) {
        Logger.d("RadioDnsLogo: Too many redirects!");
        return null;
      }
      URL base;
      try {
        base = new URL(url);
      } catch (MalformedURLException ex) {
        Logger.d(String.format("RadioDnsLogo: malformed url '%s'", url));
        return null;
      }

      conn = (HttpURLConnection) base.openConnection();
      switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
          String location = conn.getHeaderField("Location");
          location = URLDecoder.decode(location, "UTF-8");
          URL next;
          try {
            next = new URL(base, location); // Deal with relative URLs
          } catch (MalformedURLException ex) {
            Logger.d(
                String.format("RadioDnsLogo: malformed url base=%s location=%s", base, location));
            return null;
          }
          url = next.toExternalForm();
          redirect++;
          continue;
      }
      return url;
    }
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions