0

I want to read from an URL/URI the content but only if its a valid image. My approach is:

boolean isValidContent = true;
if (connection instanceof HttpURLConnection) {
    // Set Agent to avoid simulate
    ((HttpURLConnection) connection).addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64)");
    ((HttpURLConnection) connection).setRequestMethod("HEAD");
    connection.connect();
    final String contentType = connection.getContentType();
    isValidContent = contentType.startsWith("image");
    if (isValidContent) {
        ((HttpURLConnection) connection).setRequestMethod("GET");
    }
}
if (isValidContent) {
    img = Channels.newChannel(connection.getInputStream());
}

But somehow with the second attempt to read I fail with a

java.lang.IllegalStateException: connect in progress
   at java.base/sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:568)

How to reset the connection to get the full content? Is there an easier approach than mine?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
LeO
  • 4,238
  • 4
  • 48
  • 88

0 Answers0