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 testDownloadPngFile() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/fileserver/png", HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode());
    String contentType = urlConn.getHeaderField(HttpHeaders.Names.CONTENT_TYPE);
    Assert.assertTrue(contentType.equalsIgnoreCase("image/png"));
    InputStream downStream = urlConn.getInputStream();
    File file = new File(Resources.getResource("testPngFile.png").toURI());
    Assert.assertTrue(isStreamEqual(downStream, new FileInputStream(file)));
}

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

@Test
public void testDownloadJpgFile() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/fileserver/jpg", HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode());
    String contentType = urlConn.getHeaderField(HttpHeaders.Names.CONTENT_TYPE);
    Assert.assertTrue(contentType.equalsIgnoreCase("image/jpeg"));
    InputStream downStream = urlConn.getInputStream();
    File file = new File(Resources.getResource("testJpgFile.jpg").toURI());
    Assert.assertTrue(isStreamEqual(downStream, new FileInputStream(file)));
}

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

@Test
public void testDownloadTxtFile() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/fileserver/txt", HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode());
    String contentType = urlConn.getHeaderField(HttpHeaders.Names.CONTENT_TYPE);
    Assert.assertTrue(contentType.equalsIgnoreCase("text/plain"));
    InputStream downStream = urlConn.getInputStream();
    File file = new File(Resources.getResource("testTxtFile.txt").toURI());
    Assert.assertTrue(isStreamEqual(downStream, new FileInputStream(file)));
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java

@NotNull
protected Tuple2<Integer, JsonNode> fetchJson(final String rel, final boolean post) throws Exception {
    final JsonFactory factory = new JsonFactory();
    final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection();
    try {//  www.ja va 2  s  .  c  om
        conn.setRequestMethod(post ? "POST" : "GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.connect();

        final int responseCode = conn.getResponseCode();

        InputStream in;
        try {
            in = conn.getInputStream();
        } catch (final IOException e) {
            in = conn.getErrorStream();
        }
        if (in == null) {
            return Tuple2.tuple2(responseCode, (JsonNode) MissingNode.getInstance());
        }

        assertEquals("application/json", conn.getHeaderField("Content-Type"));

        try {
            final ObjectMapper om = new ObjectMapper();
            return Tuple2.tuple2(responseCode, om.reader().with(factory).readTree(in));
        } finally {
            in.close();
        }
    } finally {
        conn.disconnect();
    }
}

From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java

@Override
public boolean hasXSeraphLoginReason(String urlString, String username, String password) {
    URL url;/*from   w w  w  . j  av  a2s.  com*/
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    }

    try {
        HttpURLConnection httpConnection;

        if (proxyService == null) {
            httpConnection = (HttpURLConnection) url.openConnection();
        } else {
            httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy);
        }

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        String headerResult = httpConnection.getHeaderField("X-Seraph-LoginReason");

        return headerResult != null && headerResult.equals("AUTHENTICATION_DENIED");
    } catch (IOException e) {
        LOG.warn("IOException encountered while trying to find the response code.", e);
    }
    return false;
}

From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private String getResultFromHttp(final String location, final JSONObject object)
        throws ExternalDbUnavailableException {
    HttpURLConnection conn = null;
    try {// www .ja  v a2s. com
        URL url = new URL(location);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);

        OutputStreamWriter stream = new OutputStreamWriter(conn.getOutputStream(), Charset.defaultCharset());
        stream.write(object.toString());
        stream.flush();

        int status = conn.getResponseCode();

        while (true) {
            String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER);
            long wait = 0;

            if (header != null) {
                wait = Integer.valueOf(header);
            }

            if (wait == 0) {
                break;
            }

            LOGGER.info(String.format(WAITING_FORMAT, wait));
            conn.disconnect();

            Thread.sleep(wait * MILLIS_IN_SECOND);

            conn = (HttpURLConnection) new URL(location).openConnection();
            conn.setDoInput(true);
            conn.connect();
            status = conn.getResponseCode();
        }
        return getHttpResult(status, location, conn);
    } catch (IOException | InterruptedException | ExternalDbUnavailableException e) {
        throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e);

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

/**
 * Implement a simple proxy/*  w w w . j a v a2 s . c  o m*/
 *
 * @param requestedURL the requested URL
 * @param req the HttpServletRequest
 * @return
 */
@GET
@Path("proxy")
public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL,
        @Context HttpServletRequest req) {

    BufferedReader in = null;

    try {
        URL url = new URL(requestedURL);
        URLConnection urlConnection = url.openConnection();

        int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout();

        // Set base properties
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec

        String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT);
        if (StringUtils.isNotBlank(acceptedDataFormat)) {
            urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat);
        }

        // Open the connection
        urlConnection.connect();

        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;

            int statusCode = httpConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // Follow the redirect
                String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION);
                httpConnection.disconnect();

                if (StringUtils.isNotBlank(newLocation)) {
                    return this.proxy(newLocation, req);
                } else {
                    return Response.status(statusCode).build();
                }
            } else if (statusCode == HttpURLConnection.HTTP_OK) {

                // Send the response
                StringBuilder sbf = new StringBuilder();

                // Check if the contentType is supported
                boolean contentTypeSupported = false;
                String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE);
                List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes();
                if (contentType != null) {
                    for (String cMime : supportedMimeTypes) {
                        if (contentType.equals(cMime) || contentType.contains(cMime)) {
                            contentTypeSupported = true;
                            break;
                        }
                    }
                }

                if (!contentTypeSupported) {
                    httpConnection.disconnect();
                    return Response.status(Status.NOT_ACCEPTABLE).build();
                }

                String contentEncoding = httpConnection.getContentEncoding();
                if (StringUtils.isBlank(contentEncoding)) {
                    contentEncoding = "UTF-8";
                }

                InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(),
                        Charset.forName(contentEncoding));
                in = new BufferedReader(inStrem);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sbf.append(inputLine);
                    sbf.append("\r\n");
                }

                in.close();
                httpConnection.disconnect();

                return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType)
                        .entity(sbf.toString()).build();

            } else {
                httpConnection.disconnect();
                return Response.status(statusCode).build();
            }
        }

        return Response.status(Status.BAD_REQUEST).build();

    } catch (MalformedURLException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.BAD_REQUEST).build();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
}

From source file:com.difference.historybook.proxy.ProxyTest.java

@Test
public void testChunkedResponseHandling() throws IOException {
    String fileName = "src/test/resources/__files/response.txt";
    Path path = Paths.get(fileName).toAbsolutePath();
    byte[] body = Files.readAllBytes(path);

    stubFor(get(urlEqualTo("/some/page")).willReturn(
            aResponse().withStatus(200).withHeader("Content-Type", "text/html").withBodyFile("response.txt")));

    Proxy proxy = getProxy().setPort(PROXY_PORT);
    try {/*  w w  w  .  ja  va 2  s. co  m*/
        proxy.start();

        java.net.Proxy proxyServer = new java.net.Proxy(java.net.Proxy.Type.HTTP,
                new InetSocketAddress("127.0.0.1", PROXY_PORT));
        HttpURLConnection connection = (HttpURLConnection) new URL(
                "http://localhost:" + DUMMY_SERVER_PORT + "/some/page").openConnection(proxyServer);

        // The purpose of this test is to test chunked response handling, but there doesn't seem
        // to be an easy way to force this in WireMock (or any of the other tools I looked at)
        // Having it response with the content of a file seems to result in it switching to 
        // chunked responses, but there isn't a reason this needs to be the case.
        // The following test is really testing to make sure this test is still working
        // and forcing chunked mode responses.
        assertEquals("chunked", connection.getHeaderField("Transfer-Encoding"));

        byte[] fetchedContent = IOUtils.toByteArray(connection.getInputStream());
        assertArrayEquals(body, fetchedContent);

        proxy.stop();
    } catch (Exception e) {
        fail(e.getLocalizedMessage());
    }

}

From source file:net.mceoin.cominghome.api.NestUtil.java

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *//*w  ww.  j a  v a  2 s .  c o  m*/
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

    String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth="
            + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

            //                System.out.println("Redirect to URL : " + newUrl);

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    if (error) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java

public MoodleSession getMoodleSession(TequilaToken iTequilaToken) throws TException {
    System.out.println("getMoodleSession");
    try {/* w  ww .ja  v  a  2s . c o  m*/
        HttpURLConnection conn2 = (HttpURLConnection) new URL("http://moodle.epfl.ch/auth/tequila/index.php")
                .openConnection();
        conn2.setRequestProperty("Cookie", iTequilaToken.getLoginCookie());
        conn2.setInstanceFollowRedirects(false);
        conn2.getInputStream();
        if ("http://moodle.epfl.ch/my/".equals(conn2.getHeaderField("Location")))
            return new MoodleSession(iTequilaToken.getLoginCookie());
        else
            throw new TException("Authentication failed");
    } catch (IOException e) {
        e.printStackTrace();
        throw new TException("Failed to getMoodleSession from upstream server");
    }
}