401 message return on Java but OK on browser


Hi there, I’m trying to use the JSON feature with the flightXML2.0. When I build the URL (below) and request it via a web browser - it works (that is - I get a valid reply with valid data).


When testing under Java I get the notorious 401 message

URL url = new URL("http://hexa:MY_KEY@flightxml.flightaware.com/json/FlightXML2/MetarEx?airport=KJFK&startTime=0&howMany=1&offset=0");

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Accept", "application/json");

Exception in thread “main” java.io.IOException: Server returned HTTP response code: 401 for URL:

	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1459)
	at com.flightaware1.RunTest1.main(RunTest1.java:23)

Any idea why I can’t get the reply just as if I post it in a web browser? Many thanks!


HTTP 401 means you have not supplied the Authorization header in the request with your API credentials. You must use HTTP Basic Auth with your username and your FlightXML API key as your password.


I’m pasting here a java snapshot of my code with your pointer. Still get the 401 error. Wonder if you can assist what I’m doing wrong. Thanks

	public static void test2()  throws Exception
		try {
			String webPage = "http://flightxml.flightaware.com/json/FlightXML2/MetarEx?airport=KJFK&startTime=0&howMany=1&offset=0";
			String name = "hexa";
			String password = "MY_PASSWORD";

			String authString = name + ":" + password;
			System.out.println("auth string: " + authString);
			byte] authEncBytes = Base64.encodeBase64(authString.getBytes());
			String authStringEnc = new String(authEncBytes);
			System.out.println("Base64 encoded auth string: " + authStringEnc);

			URL url = new URL(webPage);
			URLConnection urlConnection = url.openConnection();
			urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
			InputStream is = urlConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);

			int numCharsRead;
			char] charArray = new char[1024];
			StringBuffer sb = new StringBuffer();
			while ((numCharsRead = isr.read(charArray)) > 0) {
				sb.append(charArray, 0, numCharsRead);
			String result = sb.toString();

			System.out.println("*** BEGIN ***");
			System.out.println("*** END ***");
		} catch (MalformedURLException e) {
		} catch (IOException e) {


Make sure you are using your FlightXML API key and not your website password for “MY_PASSWORD”

The code looks fine otherwise.