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:com.spotify.helios.client.DefaultHttpConnector.java

@Override
public HttpURLConnection connect(final URI uri, final String method, final byte[] entity,
        final Map<String, List<String>> headers) throws HeliosException {
    final Endpoint endpoint = endpointIterator.next();
    final String endpointHost = endpoint.getUri().getHost();

    try {// w  w  w . ja  v a 2s  . co  m
        HttpURLConnection connection = connect0(uri, method, entity, headers, endpointHost);

        if (connection.getResponseCode() == HTTP_BAD_GATEWAY) {
            throw new HeliosException(String.format("Request to %s returned %s, master is down", uri,
                    connection.getResponseCode()));
        }
        return connection;

    } catch (ConnectException | SocketTimeoutException | UnknownHostException e) {
        // UnknownHostException happens if we can't resolve hostname into IP address.
        // UnknownHostException's getMessage method returns just the hostname which is a
        // useless message, so log the exception class name to provide more info.
        log.debug(e.toString());
        throw new HeliosException("Unable to connect to master", e);
    } catch (IOException e) {
        throw new HeliosException(e);
    }
}

From source file:blueprint.sdk.google.gcm.GcmSender.java

/**
 * gets response code/*from   ww w  .  j a va2  s.  c o m*/
 *
 * @param http HTTP connection
 * @return 200: http ok, 6xx: {@link GcmResponse}, others: http error
 * @throws IOException
 */
@SuppressWarnings("IndexOfReplaceableByContains")
private int getResponseCode(HttpURLConnection http) throws IOException {
    int result = http.getResponseCode();

    if (result == HttpURLConnection.HTTP_OK) {
        int contentLength = http.getContentLength();
        String contentType = http.getContentType();
        if (0 == contentLength) {
            result = GcmResponse.ERR_NO_CONTENT;
        } else if (Validator.isEmpty(contentType)) {
            result = GcmResponse.ERR_NO_CONTENT_TYPE;
        } else if (0 > contentType.indexOf("application/json")) {
            result = GcmResponse.ERR_NOT_JSON;
        } else {
            result = 200;
        }
    }

    return result;
}

From source file:com.ttl.googleplus.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *///w  w w.ja  va  2  s.  c o  m
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }

    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();

        String name = getFirstName(readResponse(is));
        Log.d("profile data", readResponse(is));

        mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandlerITest.java

private JsonNode findNumericDataOnServer() throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(findNumericDataUrl).openConnection();
    urlConnection.connect();//  w  ww  .j av a  2 s  .  c  o  m
    int responseCode = urlConnection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try (InputStream inputStream = urlConnection.getInputStream()) {
        return objectMapper.readTree(inputStream);
    }
}

From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java

@Override
public TransportFetch httpGetOtherFile(String uri) {
    TransportFetch result;/*from   w w w .  j a  v  a2  s  .  co m*/
    try {
        final URL url = new URL(serverURL + uri);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        final int responseCode = conn.getResponseCode();
        final String responseMessage = conn.getResponseMessage();
        InputStream responseIn = conn.getErrorStream();
        if (responseIn == null) {
            responseIn = conn.getInputStream();
        }

        // Read the body to the output if OK otherwise to the error message
        final byte[] body = IOUtils.toByteArray(responseIn);

        result = new TransportFetch(responseCode, responseMessage, body);
    } catch (MalformedURLException ex) {
        LOG.error("Malformed URL", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    } catch (IOException ex) {
        LOG.error("IO error", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    }

    return result;
}

From source file:org.akvo.flow.api.FlowApi.java

private int getStatusCode(HttpURLConnection conn) throws IOException {
    try {//from  ww  w.  j  a v  a 2s  . com
        return conn.getResponseCode();
    } catch (IOException e) {
        // HttpUrlConnection will throw an IOException if any 4XX
        // response is sent. If we request the status again, this
        // time the internal status will be properly set, and we'll be
        // able to retrieve it.
        return conn.getResponseCode();
    }
}

From source file:com.giga.warehouse.RestExampleIT.java

@Test
public void shouldAccessInitialPage() throws Exception {
    URL url = new URL("http://localhost:8181/modeshape-rest-example/restful-services/warehouse");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    //connection.set

    assertEquals(200, connection.getResponseCode());

    System.out.println(IOUtils.toString(connection.getInputStream()));
    System.out.println(connection.getContentType());

}

From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java

@Override
public TransportFetch httpGetTheFile() {
    TransportFetch result;//from w  w w  .j  a  va2s  . c  o  m
    try {
        final URL url = new URL(serverURL + theFileURI);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        final int responseCode = conn.getResponseCode();
        final String responseMessage = conn.getResponseMessage();
        InputStream responseIn = conn.getErrorStream();
        if (responseIn == null) {
            responseIn = conn.getInputStream();
        }

        // Read the body to the output if OK otherwise to the error message
        final byte[] body = IOUtils.toByteArray(responseIn);

        this.targetResponse = new TargetResponse(responseCode, conn.getHeaderFields(), body);

        result = new TransportFetch(responseCode, responseMessage, body);
    } catch (MalformedURLException ex) {
        LOG.error("Malformed URL", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    } catch (IOException ex) {
        LOG.error("IO error", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    }

    return result;
}

From source file:eu.openanalytics.shinyproxy.ShinyProxyTestStrategy.java

@Override
public boolean testProxy(Proxy proxy) {

    int totalWaitMs = Integer.parseInt(environment.getProperty("proxy.container-wait-time", "20000"));
    int waitMs = Math.min(2000, totalWaitMs);
    int maxTries = totalWaitMs / waitMs;
    int timeoutMs = Integer.parseInt(environment.getProperty("proxy.container-wait-timeout", "5000"));

    if (proxy.getTargets().isEmpty())
        return false;
    URI targetURI = proxy.getTargets().values().iterator().next();

    return retry(i -> {
        try {//w  w  w  .  j  av  a 2 s. c  o m
            URL testURL = new URL(targetURI.toString());
            HttpURLConnection connection = ((HttpURLConnection) testURL.openConnection());
            connection.setConnectTimeout(timeoutMs);
            int responseCode = connection.getResponseCode();
            if (responseCode == 200)
                return true;
        } catch (Exception e) {
            if (i > 1 && log != null)
                log.warn(String.format("Container unresponsive, trying again (%d/%d): %s", i, maxTries,
                        targetURI));
        }
        return false;
    }, maxTries, waitMs, false);
}