URLConnection, cannot find symbol

1.4k Views Asked by At

I´m trying to get a header field with the following code:

import java.net.URL;
import java.net.URLConnection;
 
public class Main {

  public static void main() {

   try {

    URL url = new URL("URL");
    URLConnection con = url.openConnection();
    con.setRequestMethod("HEAD");
    con.setRequestProperty("property", "name");

    System.out.println("\nGetting Response Header By Key ...\n");
    String userToken = con.getHeaderField("parameter");

    if (userToken == null) {
        System.out.println("Key 'userToken' is not found!");
    } else {
        System.out.println("userToken - " + userToken);
     
     
    }

    System.out.println("\n Done");

    } catch (Exception e) {
       e.printStackTrace();
    }

  }
}

But I´m getting the following error:

Main.java:14: error: cannot find symbol con.setRequestMethod("HEAD"); ^ symbol: method setRequestMethod(String) location: variable con of type URLConnection 1 error

1

There are 1 best solutions below

0
Pieter12345 On

You are trying to use HttpURLConnection.setRequestMethod(String) on a URLConnection variable. Luckily, url.openConnection(); will actuall return a HttpURLConnection, so you can cast to HttpURLConnection:

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");