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:fi.elfcloud.sci.DataItem.java

/**
 * Retrieves data from {@link DataItem}.
 * @return {@link InputStream} of the server connection.
 * @throws InvalidKeyException/* w  ww. j  a  va2  s .com*/
 * @throws ECException
 * @throws ECEncryptionException
 * @see {@link InputStream}
 */
public InputStream getData() throws InvalidKeyException, ECException, ECEncryptionException {
    Map<String, String> headers = new HashMap<String, String>();
    try {
        headers.put("X-ELFCLOUD-KEY", Base64.encodeBase64String(this.name.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    headers.put("X-ELFCLOUD-PARENT", Integer.toString(this.parentId));

    HttpURLConnection conn = null;
    HashMap<String, String> metaMap;
    try {
        conn = this.client.getConnection().getData(headers);
    } catch (ECException e) {
        e.printStackTrace();
    }
    this.setHash(conn.getHeaderField("X-ELFCLOUD-HASH"));
    this.meta = conn.getHeaderField("X-ELFCLOUD-META");
    metaMap = Utils.metaToMap(this.meta);
    this.setKeyLength(Long.parseLong(conn.getHeaderField("Content-Length")));
    DataStream dataStream;
    InputStream is = null;
    try {
        is = conn.getInputStream();
    } catch (IOException e) {
        ECDataItemException exc = new ECDataItemException();
        exc.setMessage("Error with server connection");
        throw exc;
    }
    if (!metaMap.get("ENC").equalsIgnoreCase("NONE") && client.getEncryptionMode() != ENC.NONE) {
        if (metaMap.containsKey("KHA")) {
            dataStream = new DataStream(Cipher.DECRYPT_MODE, is, metaMap.get("KHA"));
        } else {
            dataStream = new DataStream(Cipher.DECRYPT_MODE, is, "");
        }
    } else {
        dataStream = new DataStream(0, is, null);
    }
    return dataStream.getStream();

}

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

@Test
public void queryESKeyColPropertyComp3() throws Exception {
    URL url = new URL(SERVICE_URI + "ESKeyNav(1)/CollPropertyComp" + "?$select=PropertyComp");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
    connection.connect();//from   ww  w.  ja  v a  2s . co  m

    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

    final String content = IOUtils.toString(connection.getInputStream());
    System.out.println("Content is::" + content);
    assertTrue(content.contains(
            "\"value\":[{\"PropertyComp\":{" + "\"PropertyString\":\"First Resource - positive values\","
                    + "\"PropertyBinary\":\"ASNFZ4mrze8=\",\"PropertyBoolean\":true,"
                    + "\"PropertyByte\":255,\"PropertyDate\":\"2012-12-03\","
                    + "\"PropertyDateTimeOffset\":\"2012-12-03T07:16:23Z\","
                    + "\"PropertyDecimal\":34,\"PropertySingle\":1.79E20,"
                    + "\"PropertyDouble\":-1.79E20,\"PropertyDuration\":\"PT6S\","
                    + "\"PropertyGuid\":\"01234567-89ab-cdef-0123-456789abcdef\","
                    + "\"PropertyInt16\":32767,\"PropertyInt32\":2147483647,"
                    + "\"PropertyInt64\":9223372036854775807,\"PropertySByte\":127,"
                    + "\"PropertyTimeOfDay\":\"21:05:59\"}},{\"PropertyComp\":"
                    + "{\"PropertyString\":\"First Resource - positive values\","
                    + "\"PropertyBinary\":\"ASNFZ4mrze8=\",\"PropertyBoolean\":true,"
                    + "\"PropertyByte\":255,\"PropertyDate\":\"2012-12-03\","
                    + "\"PropertyDateTimeOffset\":\"2012-12-03T07:16:23Z\","
                    + "\"PropertyDecimal\":34,\"PropertySingle\":1.79E20,"
                    + "\"PropertyDouble\":-1.79E20,\"PropertyDuration\":\"PT6S\","
                    + "\"PropertyGuid\":\"01234567-89ab-cdef-0123-456789abcdef\","
                    + "\"PropertyInt16\":32767,\"PropertyInt32\":2147483647,"
                    + "\"PropertyInt64\":9223372036854775807,\"PropertySByte\":127,"
                    + "\"PropertyTimeOfDay\":\"21:05:59\"}},{\"PropertyComp\":"
                    + "{\"PropertyString\":\"First Resource - positive values\","
                    + "\"PropertyBinary\":\"ASNFZ4mrze8=\",\"PropertyBoolean\":true,"
                    + "\"PropertyByte\":255,\"PropertyDate\":\"2012-12-03\","
                    + "\"PropertyDateTimeOffset\":\"2012-12-03T07:16:23Z\","
                    + "\"PropertyDecimal\":34,\"PropertySingle\":1.79E20,"
                    + "\"PropertyDouble\":-1.79E20,\"PropertyDuration\":\"PT6S\","
                    + "\"PropertyGuid\":\"01234567-89ab-cdef-0123-456789abcdef\","
                    + "\"PropertyInt16\":32767,\"PropertyInt32\":2147483647,"
                    + "\"PropertyInt64\":9223372036854775807,\"PropertySByte\":127,"
                    + "\"PropertyTimeOfDay\":\"21:05:59\"}}]"));
}

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

@Test
public void queryESCompCollDerivedWithMixedComplexTypes() throws Exception {
    URL url = new URL(SERVICE_URI + "ESCompCollDerived(12345)/" + "CollPropertyCompAno?$select=PropertyString");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full");
    connection.connect();/*from w w  w  .  j a v a 2  s.c o m*/

    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertEquals(ContentType.JSON_FULL_METADATA,
            ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

    final String content = IOUtils.toString(connection.getInputStream());
    assertTrue(content.contains("\"@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrimAno)\","
            + "\"value\":[{\"@odata.type\":\"#olingo.odata.test1.CTBaseAno\","
            + "\"PropertyString\":\"TEST12345\"},{\"@odata.type\":"
            + "\"#olingo.odata.test1.CTTwoPrimAno\",\"PropertyString\":\"TESTabcd\"}]"));
}

From source file:org.omegat.core.team2.impl.HTTPRemoteRepository.java

/**
 * Retrieve remote URL with non-modified checking by ETag. If server doesn't support ETag, file will be
 * always retrieved./*w w w.  ja v  a  2 s.com*/
 */
protected void retrieve(Properties etags, String file, String url, File out) throws Exception {
    String etag = etags.getProperty(file);
    Log.logDebug(LOGGER, "Retrieve " + url + " into " + out.getAbsolutePath() + " with ETag=" + etag);

    out.getParentFile().mkdirs();
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    try {
        if (etag != null) {
            // use ETag if we know it
            conn.setRequestProperty("If-None-Match", etag);
        }
        switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_OK:
            etag = conn.getHeaderField("ETag");
            Log.logDebug(LOGGER, "Retrieve " + url + ": 200 with ETag=" + etag);
            break;
        case HttpURLConnection.HTTP_NOT_MODIFIED:
            // not modified - just return
            Log.logDebug(LOGGER, "Retrieve " + url + ": not modified");
            return;
        default:
            throw new RuntimeException("HTTP response code: " + conn.getResponseCode());
        }

        // load into .tmp file
        File temp = new File(out.getAbsolutePath() + ".tmp");
        InputStream in = conn.getInputStream();
        try {
            FileUtils.copyInputStreamToFile(in, temp);
        } finally {
            in.close();
        }

        // rename into file
        if (out.exists()) {
            if (!out.delete()) {
                throw new IOException();
            }
        }
        if (!temp.renameTo(out)) {
            throw new IOException();
        }
        etags.setProperty(file, etag);
    } finally {
        conn.disconnect();
    }

    Log.logDebug(LOGGER, "Retrieve " + url + " finished");
}

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

@Test
public void validODataVersionAndMaxVersionHeader2() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ODATA_VERSION, "4.0");
    connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "4.0");
    connection.connect();//from  w  w  w . ja  va  2s . c o  m

    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION));
    assertEquals("application/json; odata.metadata=minimal",
            connection.getHeaderField(HttpHeader.CONTENT_TYPE));

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

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

@Test
public void validODataVersionAndMaxVersionHeader1() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ODATA_VERSION, "4.0");
    connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "4.01");
    connection.connect();//from www  . ja v  a  2s  . c  o  m

    assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
    assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION));
    assertEquals("application/json; odata.metadata=minimal",
            connection.getHeaderField(HttpHeader.CONTENT_TYPE));

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

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

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

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ODATA_VERSION, "5.0");
    connection.setRequestProperty(HttpHeader.ODATA_MAX_VERSION, "5.0");
    connection.connect();//from www.  ja v a2 s  .co  m

    assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
    assertEquals("4.0", connection.getHeaderField(HttpHeader.ODATA_VERSION));

    final String content = IOUtils.toString(connection.getErrorStream());
    assertTrue(content.contains("OData version '5.0' is not supported."));
}

From source file:eu.peppol.smp.SmpContentRetrieverImpl.java

/**
 * Gets the XML content of a given url, wrapped in an InputSource object.
 */// w  w w.  jav  a 2 s  . c  om
@Override
public InputSource getUrlContent(URL url) {

    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
    } catch (IOException e) {
        throw new IllegalStateException("Unable to connect to " + url + " ; " + e.getMessage(), e);
    }

    try {
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE)
            throw new TryAgainLaterException(url, httpURLConnection.getHeaderField("Retry-After"));
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(url, httpURLConnection.getResponseCode());
    } catch (IOException e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

    try {

        String encoding = httpURLConnection.getContentEncoding();
        InputStream in = new BOMInputStream(httpURLConnection.getInputStream());
        InputStream result;

        if (encoding != null && encoding.equalsIgnoreCase(ENCODING_GZIP)) {
            result = new GZIPInputStream(in);
        } else if (encoding != null && encoding.equalsIgnoreCase(ENCODING_DEFLATE)) {
            result = new InflaterInputStream(in);
        } else {
            result = in;
        }

        String xml = readInputStreamIntoString(result);

        return new InputSource(new StringReader(xml));

    } catch (Exception e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

}

From source file:CloudManagerAPI.java

private String getLocation(HttpURLConnection connection) {
    return connection.getHeaderField("Location");
}

From source file:org.dataconservancy.dcs.util.droid.DroidSignatureFileManager.java

/**
 * Checks if the url of the of the file exists and then downloads it to the provided file if it does.
 * @param fileUrl The url of the file to retrieve.
 * @param signatureFile The file object that should be used to store the contents of the file at the url.
 * @return True if the url was found and the contents were able to be stored in the file, false otherwise.
 *///from w w w  .  j a v  a 2  s .  c  om
private boolean downloadLatestFile(URL fileUrl, File signatureFile) {
    boolean fileRetrieved = true;
    log.info("Attempting to download droid file: " + fileUrl);
    String contentType = "";
    try {
        HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("GET");
        connection.connect();
        contentType = connection.getHeaderField("Content-Type");
    } catch (IOException e) {
        fileRetrieved = false;
        log.error("Error connection to file url: " + fileUrl + " Exception: " + e.getMessage());
    }

    if (fileRetrieved) {
        //National Archives website returns 200 even if the url doesn't exist, so check to make sure the content type is xml and not html
        if (contentType.equalsIgnoreCase("text/xml")) {
            try {
                FileUtils.copyURLToFile(fileUrl, signatureFile);
            } catch (IOException e) {
                fileRetrieved = false;
                log.error("Error connection to file url: " + fileUrl + " Exception: " + e.getMessage());
            }
            log.info("Successfully downloaded droid file: " + fileUrl);
        } else {
            fileRetrieved = false;
        }
    }
    return fileRetrieved;
}