Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

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

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:org.apache.hadoop.http.TestHttpServerLogs.java

@Test
public void testLogsDisabled() throws Exception {
    Configuration conf = new Configuration();
    conf.setBoolean(CommonConfigurationKeysPublic.HADOOP_HTTP_LOGS_ENABLED, false);
    startServer(conf);/*  w  ww  . j a v  a2 s  .  c  om*/
    URL url = new URL(baseUrl + "/logs");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    assertEquals(HttpStatus.SC_NOT_FOUND, conn.getResponseCode());
}

From source file:org.jboss.as.test.integration.management.console.WebConsoleRedirectionTestCase.java

@Test
public void testRedirectionInNormalMode() throws Exception {
    final HttpURLConnection connection = getConnection();
    assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode());
    String location = connection.getHeaderFields().get(Headers.LOCATION_STRING).get(0);
    assertEquals("/console/index.html", location);
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

private static double requestDogeBtcConversion(int provider) {
    HttpURLConnection connection = null;
    Reader reader = null;/*from   w w  w.  j  a va 2  s.c  o  m*/
    URL providerUrl;
    switch (provider) {
    case 0:
        providerUrl = CRYPTSY_URL;
        break;
    case 1:
        providerUrl = BTER_URL;
        break;
    default:
        providerUrl = CRYPTSY_URL;
        break;
    }

    try {
        connection = (HttpURLConnection) providerUrl.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            try {
                final JSONObject json = new JSONObject(content.toString());
                double rate;
                boolean success;
                switch (provider) {
                case 0:
                    success = json.getBoolean("success");
                    if (!success) {
                        return -1;
                    }
                    rate = json.getJSONObject("data").getJSONObject("last_trade").getDouble("price");
                    break;
                case 1:
                    success = json.getString("result").equals("true"); // Eww bad API!
                    if (!success) {
                        return -1;
                    }
                    rate = Double.valueOf(json.getString("last"));
                    break;
                default:
                    return -1;
                }
                return rate;
            } catch (NumberFormatException e) {
                log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider));
                return -1;
            }

        } else {
            log.debug("http status " + responseCode + " when fetching " + providerUrl);
        }
    } catch (final Exception x) {
        log.debug("problem reading exchange rates", x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return -1;
}

From source file:com.spotify.helios.system.APITest.java

/**
 * Verify that the Helios master generates and returns a hash if the submitted job creation
 * request does not include one.//from w  ww .  j av  a 2 s.  c o  m
 */
@Test
public void testHashLessJobCreation() throws Exception {
    startDefaultMaster();

    final Job job = Job.newBuilder().setName(testJobName).setVersion(testJobVersion).setImage(BUSYBOX)
            .setCommand(IDLE_COMMAND).setCreatingUser(TEST_USER).build();

    // Remove the hash from the id in the json serialized job
    final ObjectNode json = (ObjectNode) Json.reader().readTree(Json.asString(job));
    json.set("id", TextNode.valueOf(testJobName + ":" + testJobVersion));

    final HttpURLConnection req = post("/jobs?user=" + TEST_USER, Json.asBytes(json));

    assertEquals(req.getResponseCode(), 200);

    final CreateJobResponse res = Json.read(toByteArray(req.getInputStream()), CreateJobResponse.class);

    assertEquals(OK, res.getStatus());
    assertTrue(res.getErrors().isEmpty());
    assertEquals(job.getId().toString(), res.getId());
}

From source file:com.forgerock.wisdom.oauth2.info.internal.GoogleIntrospectionService.java

public TokenInfo introspect(final String token) {

    String tokenInfoRequest = format("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s", token);

    try {/*from w  w  w.  jav  a 2  s. co  m*/
        HttpURLConnection connection = (HttpURLConnection) new URL(tokenInfoRequest).openConnection();
        int code = connection.getResponseCode();
        if (code != 200) {
            return TokenInfo.INVALID;
        }

        try (InputStream stream = connection.getInputStream()) {
            JsonNode node = mapper.readTree(stream);
            String[] scopes = node.get("scope").asText().split(" ");
            long expiresIn = node.get("expires_in").asLong();
            return new TokenInfo(true, expiresIn, scopes);
        }

    } catch (IOException e) {
        return TokenInfo.INVALID;
    }
}

From source file:org.jboss.as.test.integration.management.console.WebConsoleRedirectionTestCase.java

@Test
public void testRedirectionInAdminMode() throws Exception {
    ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient(), true);
    try {//ww w  . j a  v  a2  s.c  om
        final HttpURLConnection connection = getConnection();
        assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode());
        String location = connection.getHeaderFields().get(Headers.LOCATION_STRING).get(0);
        assertEquals("/consoleerror/noConsoleForAdminModeError.html", location);
    } finally {
        ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient(), false);
    }
}

From source file:de.mg.stock.server.util.HttpUtil.java

public String get(String urlStr) {

    try {/*w ww . j a  v  a 2s. co  m*/
        URL url = new URL(urlStr);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream response = connection.getInputStream();
            return IOUtils.toString(response);
        } else {
            log.log(Level.WARNING, "retrieving " + urlStr + " returned " + connection.getResponseCode());
            return null;
        }
    } catch (IOException e) {
        log.log(Level.WARNING, "retrieving " + urlStr, e);
        return null;
    }
}

From source file:it.polito.tellmefirst.enhancer.BBCEnhancer.java

public String getResultFromAPI(String urlStr, String type) {

    LOG.debug("[getResultFromAPI] - BEGIN");
    String result = "";
    try {//from w w w.  ja  v a 2s  .  co  m
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Accept", type);
        if (conn.getResponseCode() != 200) {
            System.out.println(conn.getResponseMessage());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        result = sb.toString();
    } catch (Exception e) {
        LOG.error("[getResultFromAPI] - EXCEPTION: ", e);
    }
    LOG.debug("[getResultFromAPI] - END");
    return result;
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *//*  w  w w  . ja v a2  s . c om*/
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        urlConnection.connect();
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } catch (IOException e) {
        String details;
        if (urlConnection != null) {
            details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage()
                    + ")";
        } else {
            details = "";
        }
        Log.e("ExoplayerUtil", "executePost: Request failed" + details, e);
        throw e;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.aperlambda.apercommon.connection.http.HttpRequestSender.java

private HttpResponse send(HttpURLConnection connection) throws IOException {
    connection.connect();/*from  w  w  w  .  ja v  a2 s .c om*/

    if (connection.getResponseCode() != 200)
        return new HttpResponse(connection.getResponseCode());

    Map<String, String> headers = new HashMap<>();
    connection.getHeaderFields().forEach((key, value) -> headers.put(key, value.get(0)));

    String body;
    InputStream iStream = null;
    try {
        iStream = connection.getInputStream();

        String encoding = connection.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;

        body = IOUtils.toString(iStream, encoding);
    } finally {
        if (iStream != null) {
            iStream.close();
        }
    }

    if (body == null) {
        throw new IOException("Unparseable response body! \n {" + body + "}");
    }

    return new HttpResponse(connection.getResponseCode(), headers, body);
}