Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

In this page you can find the example usage for java.net HttpURLConnection getHeaderField.

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:org.wso2.msf4j.internal.router.HttpServerTest.java

@Test
public void testKeepAlive() throws IOException {
    HttpURLConnection urlConn = request("/test/v1/tweets/1", HttpMethod.PUT, true);
    writeContent(urlConn, "data");
    Assert.assertEquals(200, urlConn.getResponseCode());

    Assert.assertEquals("keep-alive", urlConn.getHeaderField(HttpHeaders.Names.CONNECTION));
    urlConn.disconnect();/*  w  w w .j  av a2s . co  m*/
}

From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java

/** FIXME: refactor
 * Gets the cookie which is needed to extract the content of aip pages.
 * (changed code from ScrapingContext.getContentAsString) 
 * @param urlConn Connection to api page (from url.openConnection())
 * @return The value of the cookie./* w  w w.  j  a v  a 2  s .c  o m*/
 * @throws IOException
 */
private String getCookie() throws IOException {
    HttpURLConnection urlConn = (HttpURLConnection) new URL("http://www.blackwell-synergy.com/help")
            .openConnection();
    String cookie = null;

    urlConn.setAllowUserInteraction(true);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(false);
    urlConn.setUseCaches(false);
    urlConn.setFollowRedirects(true);
    urlConn.setInstanceFollowRedirects(false);

    urlConn.setRequestProperty("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
    urlConn.connect();

    // extract cookie from header
    Map map = urlConn.getHeaderFields();
    cookie = urlConn.getHeaderField("Set-Cookie");
    if (cookie != null && cookie.indexOf(";") >= 0)
        cookie = cookie.substring(0, cookie.indexOf(";"));

    urlConn.disconnect();
    return cookie;
}

From source file:org.wso2.msf4j.internal.router.HttpServerTest.java

@Test
public void testHeaderResponse() throws IOException {
    HttpURLConnection urlConn = request("/test/v1/headerResponse", HttpMethod.GET);
    urlConn.addRequestProperty("name", "name1");

    Assert.assertEquals(200, urlConn.getResponseCode());
    Assert.assertEquals("name1", urlConn.getHeaderField("name"));
    urlConn.disconnect();/*w  w  w.  jav  a2s .c  o  m*/
}

From source file:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

@Test
public void testHttpRedirectToHttpss() throws Exception {
    Configuration conf = new Configuration();
    int httpPort = getRandomPort();
    int httpsPort = getRandomPort();
    String confDir = createTestDir();
    String keyStore = new File(confDir, "sdc-keystore.jks").getAbsolutePath();
    OutputStream os = new FileOutputStream(keyStore);
    IOUtils.copy(getClass().getClassLoader().getResourceAsStream("sdc-keystore.jks"), os);
    os.close();/*w  w  w .j a va  2s .  c  om*/
    conf.set(WebServerTask.AUTHENTICATION_KEY, "none");
    conf.set(WebServerTask.HTTP_PORT_KEY, httpPort);
    conf.set(WebServerTask.HTTPS_PORT_KEY, httpsPort);
    conf.set(WebServerTask.HTTPS_KEYSTORE_PATH_KEY, "sdc-keystore.jks");
    conf.set(WebServerTask.HTTPS_KEYSTORE_PASSWORD_KEY, "password");
    final WebServerTask ws = createWebServerTask(confDir, conf);
    try {
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        Thread.sleep(1000);
        HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + httpPort + "/ping")
                .openConnection();
        conn.setInstanceFollowRedirects(false);
        Assert.assertTrue(conn.getResponseCode() >= 300 && conn.getResponseCode() < 400);
        Assert.assertTrue(conn.getHeaderField("Location").startsWith("https://"));
        HttpsURLConnection conns = (HttpsURLConnection) new URL(conn.getHeaderField("Location"))
                .openConnection();
        configureHttpsUrlConnection(conns);
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conns.getResponseCode());
    } finally {
        ws.stopTask();
    }
}

From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java

@Test
public void multipleValuesInAcceptHeader1() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT,
            "application/json," + "application/json;q=0.1,application/json;q=0.8");
    connection.connect();//from w w w  .  j a  va  2 s . co m

    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
    ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
    assertEquals("application", contentType.getType());
    assertEquals("json", contentType.getSubtype());
    assertEquals(1, contentType.getParameters().size());
    assertEquals("minimal", contentType.getParameter("odata.metadata"));

    final String content = IOUtils.toString(connection.getInputStream());
    assertNotNull(content);
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public void getCaptcha(String image) {

    try {/*from w ww. j a  va 2  s  .  c  o  m*/
        URL obj = new URL(image);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.addRequestProperty("Connection", "keep-alive");

        con.getResponseCode();
        tokenCookie = con.getHeaderField("Set-Cookie");

        // creating the input stream from google image
        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
        // my local file writer, output stream
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Captcha.png"));
        // until the end of data, keep saving into file.
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
        out.flush();
        in.close();
        out.close();
        con.disconnect();
    } catch (MalformedURLException e) {

    } catch (IOException e) {
        // TODO: handle exception
    }

}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

/**
 * From the <code>HttpURLConnection</code>, store all the "set-cookie"
 * key-pair values in the cookieManager of the <code>UrlConfig</code>.
 *
 * @param conn//from  ww  w  .  j a va2 s. c  om
 *            <code>HttpUrlConnection</code> which represents the URL
 *            request
 * @param u
 *            <code>URL</code> of the URL request
 * @param cookieManager
 *            the <code>CookieManager</code> containing all the cookies
 *            for this <code>UrlConfig</code>
 */
private void saveConnectionCookies(HttpURLConnection conn, URL u, CookieManager cookieManager) {
    if (cookieManager != null) {
        for (int i = 1; conn.getHeaderFieldKey(i) != null; i++) {
            if (conn.getHeaderFieldKey(i).equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                cookieManager.addCookieFromHeader(conn.getHeaderField(i), u);
            }
        }
    }
}

From source file:org.apache.cactus.client.authentication.FormAuthentication.java

/**
 * Get a cookie required to be set by set-cookie header field.
 * @param theConnection a {@link HttpURLConnection}
 * @param theTarget the target cookie name
 * @return the {@link Cookie}//from  ww w.j av a2 s. c  o m
 */
private Cookie getCookie(HttpURLConnection theConnection, String theTarget) {
    // Check (possible multiple) cookies for a target.
    int i = 1;
    String key = theConnection.getHeaderFieldKey(i);
    while (key != null) {
        if (key.equalsIgnoreCase("set-cookie")) {
            // Cookie is in the form:
            // "NAME=VALUE; expires=DATE; path=PATH;
            //  domain=DOMAIN_NAME; secure"
            // The only thing we care about is finding a cookie with
            // the name "JSESSIONID" and caching the value.
            String cookiestr = theConnection.getHeaderField(i);
            String nameValue = cookiestr.substring(0, cookiestr.indexOf(";"));
            int equalsChar = nameValue.indexOf("=");
            String name = nameValue.substring(0, equalsChar);
            String value = nameValue.substring(equalsChar + 1);
            if (name.equalsIgnoreCase(theTarget)) {
                return new Cookie(theConnection.getURL().getHost(), name, value);
            }
        }
        key = theConnection.getHeaderFieldKey(++i);
    }
    return null;
}

From source file:com.laurencedawson.image_management.ImageManager.java

/**
 * Grab and save an image directly to disk
 * @param file The Bitmap file//  w w  w.  j  av a2 s  .  co  m
 * @param url The URL of the image
 * @param imageCallback The callback associated with the request
 */
public static void cacheImage(final File file, ImageRequest imageCallback) {

    HttpURLConnection urlConnection = null;
    FileOutputStream fileOutputStream = null;
    InputStream inputStream = null;
    boolean isGif = false;

    try {
        // Setup the connection
        urlConnection = (HttpURLConnection) new URL(imageCallback.mUrl).openConnection();
        urlConnection.setConnectTimeout(ImageManager.LONG_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(ImageManager.LONG_REQUEST_TIMEOUT);
        urlConnection.setUseCaches(true);
        urlConnection.setInstanceFollowRedirects(true);

        // Set the progress to 0
        imageCallback.sendProgressUpdate(imageCallback.mUrl, 0);

        // Connect
        inputStream = urlConnection.getInputStream();

        // Do not proceed if the file wasn't downloaded
        if (urlConnection.getResponseCode() == 404) {
            urlConnection.disconnect();
            return;
        }

        // Check if the image is a GIF
        String contentType = urlConnection.getHeaderField("Content-Type");
        if (contentType != null) {
            isGif = contentType.equals(GIF_MIME);
        }

        // Grab the length of the image
        int length = 0;
        try {
            String fileLength = urlConnection.getHeaderField("Content-Length");
            if (fileLength != null) {
                length = Integer.parseInt(fileLength);
            }
        } catch (NumberFormatException e) {
            if (ImageManager.DEBUG) {
                e.printStackTrace();
            }
        }

        // Write the input stream to disk
        fileOutputStream = new FileOutputStream(file, true);
        int byteRead = 0;
        int totalRead = 0;
        final byte[] buffer = new byte[8192];
        int frameCount = 0;

        // Download the image
        while ((byteRead = inputStream.read(buffer)) != -1) {

            // If the image is a gif, count the start of frames
            if (isGif) {
                for (int i = 0; i < byteRead - 3; i++) {
                    if (buffer[i] == 33 && buffer[i + 1] == -7 && buffer[i + 2] == 4) {
                        frameCount++;

                        // Once we have at least one frame, stop the download
                        if (frameCount > 1) {
                            fileOutputStream.write(buffer, 0, i);
                            fileOutputStream.close();

                            imageCallback.sendProgressUpdate(imageCallback.mUrl, 100);
                            imageCallback.sendCachedCallback(imageCallback.mUrl, true);

                            urlConnection.disconnect();
                            return;
                        }
                    }
                }
            }

            // Write the buffer to the file and update the total number of bytes
            // read so far (used for the callback)
            fileOutputStream.write(buffer, 0, byteRead);
            totalRead += byteRead;

            // Update the callback with the current progress
            if (length > 0) {
                imageCallback.sendProgressUpdate(imageCallback.mUrl,
                        (int) (((float) totalRead / (float) length) * 100));
            }
        }

        // Tidy up after the download
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }

        // Sent the callback that the image has been downloaded
        imageCallback.sendCachedCallback(imageCallback.mUrl, true);

        if (inputStream != null) {
            inputStream.close();
        }

        // Disconnect the connection
        urlConnection.disconnect();
    } catch (final MalformedURLException e) {
        if (ImageManager.DEBUG) {
            e.printStackTrace();
        }

        // If the file exists and an error occurred, delete the file
        if (file != null) {
            file.delete();
        }

    } catch (final IOException e) {
        if (ImageManager.DEBUG) {
            e.printStackTrace();
        }

        // If the file exists and an error occurred, delete the file
        if (file != null) {
            file.delete();
        }

    }

}

From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java

@Test
public void testUpdateResponse_HEAD() throws Exception {
    String query = "INSERT DATA { <foo:foo> <foo:bar> \"foo\". } ";
    String location = Protocol.getStatementsLocation(TestServer.REPOSITORY_URL);
    location += "?update=" + URLEncoder.encode(query, "UTF-8");

    URL url = new URL(location);

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

    conn.connect();/*from w  w w  .  ja  va2  s. c om*/

    try {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String contentType = conn.getHeaderField("Content-Type");
            assertNotNull(contentType);

            // snip off optional charset declaration
            int charPos = contentType.indexOf(";");
            if (charPos > -1) {
                contentType = contentType.substring(0, charPos);
            }

            assertEquals(0, conn.getContentLength());
        } else {
            String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
                    + responseCode + ")";
            fail(response);
            throw new RuntimeException(response);
        }
    } finally {
        conn.disconnect();
    }
}