/** * Connects to the given URL using a HEAD request to retreive * the headers sent in the response. */ public static Value get_headers(Env env, string urlString, @Optional Value format) { Socket socket = null; try { URL url = new URL(urlString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { env.warning(L.l("Not an HTTP URL")); return(null); } int port = 80; if (url.getPort() < 0) { if (url.getProtocol().equals("http")) { port = 80; } else if (url.getProtocol().equals("https")) { port = 443; } } else { port = url.getPort(); } socket = new Socket(url.getHost(), port); OutputStream @out = socket.getOutputStream(); InputStream in = socket.getInputStream(); StringBuilder request = new StringBuilder(); request.append("HEAD "); if (url.getPath() != null) { request.append(url.getPath()); } if (url.getQuery() != null) { request.append("?" + url.getQuery()); } if (url.getRef() != null) { request.append("#" + url.getRef()); } request.append(" HTTP/1.0\r\n"); if (url.getHost() != null) { request.append("Host: " + url.getHost() + "\r\n"); } request.append("\r\n"); OutputStreamWriter writer = new OutputStreamWriter(out); writer.write(request.ToString()); writer.flush(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(in)); ArrayValue result = new ArrayValueImpl(); if (format.toBoolean()) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); if (line.length() == 0) { continue; } int colon = line.indexOf(':'); ArrayValue values; if (colon < 0) { result.put(env.createString(line.trim())); } else { StringValue key = env.createString(line.substring(0, colon).trim()); StringValue value; if (colon < line.length()) { value = env.createString(line.substring(colon + 1).trim()); } else { value = env.getEmptyString(); } if (result.get(key) != UnsetValue.UNSET) { values = (ArrayValue)result.get(key); } else { values = new ArrayValueImpl(); result.put(key, values); } values.put(value); } } // collapse single entries for (Value key : result.keySet()) { Value value = result.get(key); if (value.isArray() && ((ArrayValue)value).getSize() == 1) { result.put(key, ((ArrayValue)value).get(LongValue.ZERO)); } } } else { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); if (line.length() == 0) { continue; } result.put(env.createString(line.trim())); } } return(result); } catch (Exception e) { env.warning(e); return(BooleanValue.FALSE); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { env.warning(e); } } }