Example usage for java.net URLConnection getHeaderFieldKey

List of usage examples for java.net URLConnection getHeaderFieldKey

Introduction

In this page you can find the example usage for java.net URLConnection getHeaderFieldKey.

Prototype

public String getHeaderFieldKey(int n) 

Source Link

Document

Returns the key for the n th header field.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    URL url = new URL("http://java2s.com");
    URLConnection conn = url.openConnection();

    for (int i = 0;; i++) {
        String headerName = conn.getHeaderFieldKey(i);
        String headerValue = conn.getHeaderField(i);
        System.out.println(headerName);
        System.out.println(headerValue);

        if (headerName == null && headerValue == null) {
            System.out.println("No more headers");
            break;
        }/*from  w w  w .j av a 2  s .  c  om*/
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    URL url = new URL("http://hostname:80");
    URLConnection conn = url.openConnection();

    for (int i = 0;; i++) {
        String headerName = conn.getHeaderFieldKey(i);
        String headerValue = conn.getHeaderField(i);
        System.out.println(headerName);
        System.out.println(headerValue);

        if (headerName == null && headerValue == null) {
            System.out.println("No more headers");
            break;
        }//from   w  w  w  .ja  v a  2s  .co m
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    URL url = new URL("http://hostname:80");
    URLConnection conn = url.openConnection();

    for (int i = 0;; i++) {
        String headerName = conn.getHeaderFieldKey(i);
        String headerValue = conn.getHeaderField(i);

        if (headerName == null && headerValue == null) {
            break;
        }/*from   w  w w  .j a va  2  s  .  c  om*/
        if ("Set-Cookie".equalsIgnoreCase(headerName)) {
            String[] fields = headerValue.split(";\\s*");
            for (int j = 1; j < fields.length; j++) {
                if ("secure".equalsIgnoreCase(fields[j])) {
                    System.out.println("secure=true");
                } else if (fields[j].indexOf('=') > 0) {
                    String[] f = fields[j].split("=");
                    if ("expires".equalsIgnoreCase(f[0])) {
                        System.out.println("expires" + f[1]);
                    } else if ("domain".equalsIgnoreCase(f[0])) {
                        System.out.println("domain" + f[1]);
                    } else if ("path".equalsIgnoreCase(f[0])) {
                        System.out.println("path" + f[1]);
                    }
                }
            }
        }
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    URL u;/*  w w w . jav  a2  s  . c o  m*/
    URLConnection uc;
    String header;

    try {
        u = new URL("http://www.java2s.com");
        uc = u.openConnection();
        for (int j = 1;; j++) {
            header = uc.getHeaderField(j);
            if (header == null)
                break;
            System.out.println(uc.getHeaderFieldKey(j) + " " + header);
        }
    } catch (MalformedURLException e) {
        System.err.println("not a URL I understand.");
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:org.chililog.server.workbench.ApiUtils.java

/**
 * Gets the headers//from   w  w w .  j av a 2 s.  c  o m
 * 
 * @param conn
 * @param headers
 * @return 1st response line
 */
public static String getResponseHeaders(URLConnection conn, HashMap<String, String> headers) {
    headers.clear();
    String responseCode = "";
    for (int i = 0;; i++) {
        String name = conn.getHeaderFieldKey(i);
        String value = conn.getHeaderField(i);
        if (name == null && value == null) {
            break;
        }
        if (name == null) {
            responseCode = value;
        } else {
            headers.put(name, value);
        }
    }
    return responseCode;
}

From source file:org.holistic.ws_proxy.WSProxyHelper.java

private void headers_endpoint2client(HttpServletResponse resp, URLConnection objURLConn) throws Exception {
    int m_iHeaderNumber = 1;
    String m_sHeaderName = objURLConn.getHeaderFieldKey(m_iHeaderNumber);
    for (String m_sHeaderValue = objURLConn.getHeaderField(m_iHeaderNumber); m_sHeaderName != null
            && m_sHeaderValue != null; m_sHeaderValue = objURLConn.getHeaderField(m_iHeaderNumber)) {
        if (m_sHeaderName.equalsIgnoreCase("Set-Cookie")) {
            String m_sCookie = objURLConn.getHeaderField(m_iHeaderNumber);
            if (m_sCookie != null && !m_sCookie.equals("")) {
                log.debug("EndPoint Cookie: " + m_sCookie);
                int m_posicion = m_sCookie.indexOf("=");
                String m_sCookieModificada = m_sCookie.substring(0, m_posicion) + EXTRA_COOKIE
                        + m_sCookie.substring(m_posicion);
                log.debug("Al cliente le transmito la cookie modificada: " + m_sCookieModificada);
                resp.addHeader("Set-Cookie", m_sCookieModificada);
            }/*from w ww . j av a2s  .  c  o m*/
        } else if (!m_sHeaderName.equalsIgnoreCase("Content-Length")
                && !m_sHeaderName.equalsIgnoreCase("Transfer-Encoding")) {
            if (m_sHeaderName.equalsIgnoreCase("Cache-Control")
                    && m_sHeaderValue.equalsIgnoreCase("max-age=43200")) {
                //resp.addHeader(m_sHeaderName, "post-check=43200, pre-check=3600");
                //resp.addHeader(m_sHeaderName, "post-check=300, pre-check=420, must-revalidate");
                resp.addHeader(m_sHeaderName, "post-check=600, pre-check=601");
            } else {
                resp.addHeader(m_sHeaderName, m_sHeaderValue);
                log.debug("EndPointToClient HEADER[" + m_sHeaderName + "] - VALUE[" + m_sHeaderValue + "]");
            }
        }
        m_iHeaderNumber++;
        m_sHeaderName = objURLConn.getHeaderFieldKey(m_iHeaderNumber);
    }

}

From source file:org.jboss.test.cluster.httpsessionreplication.HttpSessionReplicationUnitTestCase.java

/**
 * Makes a HTTP Connection/*  ww w . j  a  v a2s .c  om*/
 * @param urlname
 * @throws Exception
 */
private void makeConnection(String urlname) throws Exception {
    getLog().debug("Enter makeConnection");
    try {
        // Step 1: Create URLConnection for URL
        URL url = new URL(urlname);
        URLConnection conn = url.openConnection();

        // List all the response headers from the server. 
        for (int i = 0;; i++) {
            String hname = conn.getHeaderFieldKey(i);
            String hvalue = conn.getHeaderField(i);

            getLog().debug("hname=" + hname + "::" + "value=" + hvalue);
            if (hname == null && hvalue == null) {
                // No more headers
                break;
            }
            if (hname == null) {
                getLog().debug("Response from Apache=" + hvalue);
                // The header value contains the server's HTTP version
                if (hvalue.indexOf("200") < 0 && hvalue.indexOf("301") < 0 && hvalue.indexOf("302") < 0)
                    fail(urlname + " Down");
                break;
            }
        }
    } catch (Exception e) {
        getLog().debug(e);
    }
}

From source file:org.lockss.util.UrlUtil.java

/**
 * Return a list of header fields (in the format "key;fieldValue") for conn
 * @param conn URLConnection to get headers from
 * @return list of header fields (in the format "key;fieldValue") for conn
 * @throws IllegalArgumentException if a null conn is supplied
 *//*from ww w  .j  ava 2  s.  co  m*/
public static List getHeaders(URLConnection conn) {
    if (conn == null) {
        throw new IllegalArgumentException("Called with null URLConnection");
    }
    List returnList = new ArrayList();
    boolean done = false;
    for (int ix = 0; !done; ix++) {
        String headerField = conn.getHeaderField(ix);
        String headerFieldKey = conn.getHeaderFieldKey(ix);
        done = (headerField == null && headerFieldKey == null);
        if (!done) {
            returnList.add(headerFieldKey + ";" + headerField);
        }
    }
    return returnList;
}

From source file:org.chililog.server.workbench.WorkbenchServiceTest.java

/**
 * Check if our expected file types are compressed
 * /* www .j a v a2s .  co m*/
 * @throws IOException
 * @throws ParseException
 * @throws DecoderException
 */
@Test()
public void testStaticFileCompression() throws IOException, ParseException, DecoderException {
    String[] fileExtensions = new String[] { ".html", ".js", ".css", ".json", ".txt", ".xml",
            ".nocompression" };

    // Get 10K string
    String TEXT = new RandomString(1024 * 10).nextString();
    byte[] TEXT_ARRAY = TEXT.getBytes("UTF-8");

    for (String fileExtension : fileExtensions) {
        String fileName = UUID.randomUUID().toString() + fileExtension;
        File file = new File(_workbenchStaticFilesDirectory, fileName);

        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
        out.write(TEXT);
        out.close();

        // Refresh
        file = new File(file.getPath());

        // Create a URL for the desired page
        URL url = new URL("http://localhost:8989/static/testdata/" + fileName + "?testquerystring=abc");
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // Read all the compressed data
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = conn.getInputStream();
        int b;
        while ((b = is.read()) != -1) {
            os.write(b);
        }

        // Get headers
        String responseCode = "";
        HashMap<String, String> headers = new HashMap<String, String>();
        for (int i = 0;; i++) {
            String name = conn.getHeaderFieldKey(i);
            String value = conn.getHeaderField(i);
            if (name == null && value == null) {
                break;
            }
            if (name == null) {
                responseCode = value;
                _logger.debug("*** Intial Call, Response code: %s", value);
            } else {
                headers.put(name, value);
                _logger.debug("%s = %s", name, value);
            }
        }

        // Should get back a 200
        assertEquals("HTTP/1.1 200 OK", responseCode);
        assertTrue(!StringUtils.isBlank(headers.get("Date")));

        if (fileExtension != ".nocompression") {
            // Uncompress and check it out
            assertEquals("gzip", headers.get("Content-Encoding"));
            byte[] uncompressedContent = uncompress(os.toByteArray());
            for (int j = 0; j < TEXT_ARRAY.length; j++) {
                assertEquals(TEXT_ARRAY[j], uncompressedContent[j]);
            }
        }

        // Clean up
        file.delete();
    }

    return;
}

From source file:org.chililog.server.workbench.WorkbenchServiceTest.java

/**
 * Check if our 304 Not Modified is working when getting a static file.
 * //  w ww.  j  av  a2  s.  c om
 * @throws IOException
 * @throws ParseException
 */
@Test()
public void testStaticFileCache() throws IOException, ParseException {
    String TEXT = "abc\n123";

    String fileName = UUID.randomUUID().toString() + ".txt";
    File file = new File(_workbenchStaticFilesDirectory, fileName);

    FileOutputStream fos = new FileOutputStream(file);
    OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
    out.write(TEXT);
    out.close();

    // Refresh
    file = new File(file.getPath());

    // ******************************************************
    // Initial request
    // ******************************************************
    // Create a URL for the desired page
    URL url = new URL("http://localhost:8989/static/testdata/" + fileName);
    URLConnection conn = url.openConnection();

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sb = new StringBuffer();
    String str;
    while ((str = in.readLine()) != null) {
        sb.append(str + "\n");
    }
    in.close();

    assertEquals(TEXT, sb.toString().trim());

    // Get headers
    HashMap<String, String> headers = new HashMap<String, String>();
    for (int i = 0;; i++) {
        String name = conn.getHeaderFieldKey(i);
        String value = conn.getHeaderField(i);
        if (name == null && value == null) {
            break;
        }
        if (name == null) {
            _logger.debug("*** Intial Call, Response code: %s", value);
        } else {
            headers.put(name, value);
            _logger.debug("%s = %s", name, value);
        }
    }

    assertEquals("7", headers.get("Content-Length"));
    assertEquals("text/plain", headers.get("Content-Type"));

    // Check last modified should be the same as the file's last modified date
    SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
    fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    assertEquals(fmt.format(new Date(file.lastModified())), headers.get("Last-Modified"));

    // Check Expiry
    Date expires = fmt.parse(headers.get("Expires"));
    Date serverDate = fmt.parse(headers.get("Date"));
    Calendar cal = new GregorianCalendar();
    cal.setTime(serverDate);
    cal.add(Calendar.SECOND, AppProperties.getInstance().getWorkbenchStaticFilesCacheSeconds());
    assertEquals(cal.getTimeInMillis(), expires.getTime());

    // ******************************************************
    // Cache Validation
    // ******************************************************
    url = new URL("http://localhost:8989/static/testdata/" + fileName);
    conn = url.openConnection();
    conn.setIfModifiedSince(fmt.parse(headers.get("Last-Modified")).getTime());

    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuffer();
    while ((str = in.readLine()) != null) {
        sb.append(str + "\n");
    }
    in.close();

    // No content should be returned
    assertEquals("", sb.toString().trim());

    HashMap<String, String> headers2 = new HashMap<String, String>();
    String responseCode = "";
    for (int i = 0;; i++) {
        String name = conn.getHeaderFieldKey(i);
        String value = conn.getHeaderField(i);
        if (name == null && value == null) {
            break;
        }
        if (name == null) {
            responseCode = value;
            _logger.debug("*** Cache Call, Response code: %s", value);
        } else {
            headers2.put(name, value);
            _logger.debug("%s = %s", name, value);
        }
    }

    // Should get back a 304
    assertEquals("HTTP/1.1 304 Not Modified", responseCode);
    assertTrue(!StringUtils.isBlank(headers2.get("Date")));

    // ******************************************************
    // Finish
    // ******************************************************
    // Clean up
    file.delete();
}