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.apache.olingo.fit.tecsvc.http.DerivedAndMixedTypeTestITCase.java

@Test
public void queryESMixPrimWithLambdaDerived_JsonFull_Olingo1122() throws Exception {
    URL url = new URL(SERVICE_URI + "ESMixPrimCollComp?$filter=CollPropertyComp/any"
            + "(f:f/olingo.odata.test1.CTBase/AdditionalPropString%20eq%20%27ADD%20TEST%27)");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full");
    connection.connect();//  w  w  w  . ja v  a2 s  . co 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());
    final String actualContent = "\"value\":[{\"@odata.type\":\"#olingo.odata.test1.ETMixPrimCollComp\","
            + "\"@odata.id\":\"ESMixPrimCollComp(32767)\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":32767,"
            + "\"CollPropertyString@odata.type\":\"#Collection(String)\","
            + "\"CollPropertyString\":[\"Employee1@company.example\",\"Employee2@company.example\","
            + "\"Employee3@company.example\"],"
            + "\"PropertyComp\":{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":111,"
            + "\"PropertyString\":\"TEST A\","
            + "\"NavPropertyETTwoKeyNavOne@odata.navigationLink\":\"ESTwoKeyNav(PropertyInt16=1,PropertyString='1')\"},"
            + "\"CollPropertyComp@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrim)\","
            + "\"CollPropertyComp\":[{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":123,"
            + "\"PropertyString\":\"TEST 1\","
            + "\"NavPropertyETTwoKeyNavOne@odata.navigationLink\":\"ESTwoKeyNav(PropertyInt16=1,PropertyString='2')\"},"
            + "{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":456,"
            + "\"PropertyString\":\"TEST 2\","
            + "\"NavPropertyETTwoKeyNavOne@odata.navigationLink\":\"ESTwoKeyNav(PropertyInt16=1,PropertyString='2')\"},"
            + "{\"@odata.type\":\"#olingo.odata.test1.CTBase\",\"PropertyInt16@odata.type\":\"#Int16\","
            + "\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\"," + "\"AdditionalPropString\":\"ADD TEST\","
            + "\"NavPropertyETTwoKeyNavOne@odata.navigationLink\":\"ESTwoKeyNav(PropertyInt16=1,PropertyString='2')\"}],"
            + "\"#olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\":"
            + "{\"title\":\"olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\","
            + "\"target\":\"ESMixPrimCollComp(32767)/olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\"}},"
            + "{\"@odata.type\":\"#olingo.odata.test1.ETMixPrimCollComp\","
            + "\"@odata.id\":\"ESMixPrimCollComp(7)\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":7,"
            + "\"CollPropertyString@odata.type\":\"#Collection(String)\","
            + "\"CollPropertyString\":[\"Employee1@company.example\",\"Employee2@company.example\","
            + "\"Employee3@company.example\"],"
            + "\"PropertyComp\":{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\","
            + "\"PropertyInt16\":222,\"PropertyString\":\"TEST B\"},"
            + "\"CollPropertyComp@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrim)\","
            + "\"CollPropertyComp\":[{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":123,"
            + "\"PropertyString\":\"TEST 1\"},{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":456,\"PropertyString\":\"TEST 2\"},"
            + "{\"@odata.type\":\"#olingo.odata.test1.CTBase\",\"PropertyInt16@odata.type\":\"#Int16\","
            + "\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\",\"AdditionalPropString\":\"ADD TEST\"}],"
            + "\"#olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\":"
            + "{\"title\":\"olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\","
            + "\"target\":\"ESMixPrimCollComp(7)/olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\"}},"
            + "{\"@odata.type\":\"#olingo.odata.test1.ETMixPrimCollComp\",\"@odata.id\":\"ESMixPrimCollComp(0)\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":0,"
            + "\"CollPropertyString@odata.type\":\"#Collection(String)\","
            + "\"CollPropertyString\":[\"Employee1@company.example\",\"Employee2@company.example\","
            + "\"Employee3@company.example\"],"
            + "\"PropertyComp\":{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":333,\"PropertyString\":\"TEST C\"},"
            + "\"CollPropertyComp@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrim)\","
            + "\"CollPropertyComp\":[{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":123,"
            + "\"PropertyString\":\"TEST 1\"},{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrim\","
            + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":456,\"PropertyString\":\"TEST 2\"},"
            + "{\"@odata.type\":\"#olingo.odata.test1.CTBase\",\"PropertyInt16@odata.type\":\"#Int16\","
            + "\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\",\"AdditionalPropString\":\"ADD TEST\"}],"
            + "\"#olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\":"
            + "{\"title\":\"olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\","
            + "\"target\":\"ESMixPrimCollComp(0)/olingo.odata.test1.BAETMixPrimCollCompRTCTTwoPrim\"}}]";
    assertTrue(content.contains(actualContent));
}

From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java

@Override
public void run() {
    updateInfo = null;/*from  w w w. j  a v  a  2s .  c o  m*/
    PipelineState ps;
    try {
        ps = runner.getState();
    } catch (PipelineStoreException e) {
        LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e);
        return;
    }
    if (ps.getStatus() == PipelineStatus.RUNNING) {
        if (url != null) {
            Map uploadInfo = getUploadInfo();
            if (uploadInfo != null) {
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(2000);
                    conn.setReadTimeout(2000);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestProperty("content-type", APPLICATION_JSON_MIME);
                    ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo);
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        String responseContentType = conn.getHeaderField("content-type");
                        if (APPLICATION_JSON_MIME.equals(responseContentType)) {
                            updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class);
                        } else {
                            LOG.trace("Got invalid content-type '{}' from from update-check server",
                                    responseContentType);
                        }
                    } else {
                        LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(),
                                conn.getResponseMessage());
                    }
                } catch (Exception ex) {
                    LOG.trace("Could not do an update check: {}", ex.toString(), ex);
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }
    }
}

From source file:net.technicpack.launchercore.mirror.MirrorStore.java

public String getETag(String address) {
    String md5 = "";

    try {/*ww w . j  a  v a  2s .  c  om*/
        URL url = getFullUrl(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);

        String eTag = conn.getHeaderField("ETag");
        if (eTag != null) {
            eTag = eTag.replaceAll("^\"|\"$", "");
            if (eTag.length() == 32) {
                md5 = eTag;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return md5;
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Read the content length for the ZIP file.
 *
 * @return The content length in bytes or -1 failed.
 *//*from   w ww  . j  a v a2  s . co  m*/
private int getHttpFileSize() {
    HttpURLConnection conn = null;
    int length = -1;
    try {
        conn = openConnection();
        conn.setRequestMethod(HttpHead.METHOD_NAME);
        conn.connect();

        // handle re-directs
        if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
            if (setUrl(conn.getHeaderField("Location"))) {
                disconnect(conn);
                length = getHttpFileSize();
            }
        } else {
            length = conn.getContentLength();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        disconnect(conn);
    }

    log("Content length is " + length + " bytes");

    return length;
}

From source file:gribbit.util.RequestBuilder.java

/**
 * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true,
 * returns a byte[] array, otherwise returns the response as a String.
 *//*from   w ww .  j av  a  2s.c  o  m*/
private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse,
        int redirDepth) {
    if (redirDepth > 6) {
        throw new IllegalArgumentException("Too many redirects");
    }
    HttpURLConnection connection = null;
    try {
        // Add the URL query params if this is a GET request
        String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url;
        connection = (HttpURLConnection) new URL(reqURL).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(isGET ? "GET" : "POST");
        connection.setUseCaches(false);
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
                        + "Chrome/43.0.2357.125 Safari/537.36");
        if (!isGET) {
            // Send the body if this is a POST request
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            String params = WebUtils.buildQueryString(keyValuePairs);
            connection.setRequestProperty("Content-Length", Integer.toString(params.length()));
            try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) {
                w.writeBytes(params);
                w.flush();
            }
        }
        if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) {
            // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET.
            return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */
                    true, isBinaryResponse, redirDepth + 1);
        } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) {
            // For 200 OK, return the text of the response
            if (isBinaryResponse) {
                ByteArrayOutputStream output = new ByteArrayOutputStream(32768);
                IOUtils.copy(connection.getInputStream(), output);
                return output.toByteArray();
            } else {
                StringWriter writer = new StringWriter(1024);
                IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
                return writer.toString();
            }
        } else {
            throw new IllegalArgumentException(
                    "Got non-OK HTTP response code: " + connection.getResponseCode());
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e);
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception e) {
            }
        }
    }
}

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

@Test
public void formatWithAcceptCharset() throws Exception {
    URL url = new URL(SERVICE_URI + "ESAllPrim?$format=application/json;charset=utf-8");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "abc");
    connection.connect();//from  w  w  w . j  a va 2  s . c  o 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(2, contentType.getParameters().size());
    assertEquals("minimal", contentType.getParameter("odata.metadata"));
    assertEquals("utf-8", contentType.getParameter("charset"));

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

From source file:org.openrdf.http.server.ProtocolTest.java

/**
 * Checks that a suitable RDF content type is returned when accept header not
 * explicitly set./*from  w  w  w .ja  va 2s . c  o  m*/
 */
@Test
public void testContentTypeForGraphQuery3_GET() throws Exception {
    String query = "DESCRIBE <foo:bar>";
    String location = TestServer.REPOSITORY_URL;
    location += "?query=" + URLEncoder.encode(query, "UTF-8");

    URL url = new URL(location);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.connect();

    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);
            }

            RDFFormat format = Rio.getParserFormatForMIMEType(contentType)
                    .orElseThrow(Rio.unsupportedFormat(contentType));
            assertNotNull(format);
        } else {
            String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
                    + responseCode + ")";
            fail(response);
            throw new RuntimeException(response);
        }
    } finally {
        conn.disconnect();
    }
}

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

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

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpMethod.GET.name());
    connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1");
    connection.connect();//from  ww w  .  ja  va  2 s.c  om

    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(3, contentType.getParameters().size());
    assertEquals("0.1", contentType.getParameter("q"));
    assertEquals("minimal", contentType.getParameter("odata.metadata"));
    assertEquals("utf-8", contentType.getParameter("charset"));

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

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

@Test
public void testGzipCompressionWithNoGzipAccept() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/gzipfile", HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode());
    String contentEncoding = urlConn.getHeaderField(HttpHeaders.Names.CONTENT_ENCODING);
    Assert.assertTrue(contentEncoding == null || !contentEncoding.contains("gzip"));
    InputStream downStream = urlConn.getInputStream();
    Assert.assertTrue(IOUtils.toByteArray(downStream).length == IOUtils
            .toByteArray(Resources.getResource("testJpgFile.jpg").openStream()).length);
}

From source file:LNISmokeTest.java

/**
 * Implement WebDAV PUT http request./* ww  w  .  jav  a  2 s  .  c om*/
 * 
 * This might be simpler with a real HTTP client library, but
 * java.net.HttpURLConnection is part of the standard SDK and it
 * demonstrates the concepts.
 * 
 * @param lni the lni
 * @param collHandle the coll handle
 * @param packager the packager
 * @param source the source
 * @param endpoint the endpoint
 * 
 * @throws RemoteException the remote exception
 * @throws ProtocolException the protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void doPut(LNISoapServlet lni, String collHandle, String packager, String source,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String collURI = doLookup(lni, collHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, collURI, packager);
    System.err.println("DEBUG: PUT file=" + source + " to URL=" + url.toString());

    // connect with PUT method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.setDoOutput(true);
    fixBasicAuth(url, conn);
    conn.connect();

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(source);
        out = conn.getOutputStream();
        copyStream(in, out);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                log.error("Unable to close input stream", e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("Unable to close output stream", e);
            }
        }
    }

    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    // diagnostics, and get resulting new item's location if avail.
    System.err.println("DEBUG: sent " + source);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
    String loc = conn.getHeaderField("Location");
    System.err.println("RESULT: Location=" + ((loc == null) ? "NULL!" : loc));
}