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:de.forsthaus.backend.util.IpLocator.java

/**
 * Gets the content for a given url. This method makes a connection, gets
 * the response from the url./*from w w  w.j a  v a2  s.  co m*/
 * 
 * A RuntimeException is throws is the status code of the response is not
 * 200.
 * 
 * @param url
 *            The url to open.
 * @return HTML response
 * @throws IOException
 */
private static List<String> getContent(URL url) throws IOException {

    final HttpURLConnection http = (HttpURLConnection) url.openConnection();
    try {
        http.connect();

        final int code = http.getResponseCode();
        if (code != 200)
            throw new IOException(
                    "IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]");
        return getContent(http);
    } finally {
        http.disconnect();
    }
}

From source file:net.ftb.util.AppUtils.java

public static void debugConnection(URLConnection c, boolean forceDebug) {
    if (Settings.getSettings().getDebugLauncher() || forceDebug) {
        if (!(c instanceof HttpURLConnection)) {
            Logger.logDebug("Something bad just happened.");
        }/*  w  ww.jav  a  2s  .  c om*/

        // for IP we need to use reflection or pass url here and rely on dns caching
        // ref: https://community.oracle.com/thread/2149226

        HttpURLConnection conn = (HttpURLConnection) c;
        int responseCode;
        try {
            responseCode = conn.getResponseCode();
        } catch (Exception e) {
            responseCode = -1;
            Logger.logDebug("failed", e);
        }

        Logger.logDebug("Request type: " + conn.getRequestMethod());
        Logger.logDebug("URL: " + conn.getURL());
        Logger.logDebug("Response code: " + responseCode);
        Logger.logDebug("Headers:\n" + AppUtils.MapListToString(conn.getHeaderFields()));
        Logger.logDebug("Message body\n" + AppUtils.ConnectionToString(conn));
        if (conn.getURL().toString().contains("ftb.cursecdn.com")) {
            DownloadUtils.CloudFlareInspector("http://ftb.cursecdn.com/", true);
        }
    }
}

From source file:edu.xjtu.qxcamerabridge.LiveviewImageExtractor.java

private static InputStream getLiveviewInputStream(String liveviewURL)
        throws MalformedURLException, IOException {
    URL url = new URL(liveviewURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setReadTimeout(2000);/*from w  ww  .  ja  v a 2s.co m*/
    connection.connect();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        return connection.getInputStream();
    }
    return null;
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

private static boolean fileExistsOnServer(String URLName) {
    URL url;//w  w w  . ja  v  a2 s.  c  o m
    try {
        url = new URL(URLName);
        URLConnection connection = url.openConnection();

        connection.connect();

        // Cast to a HttpURLConnection
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;

            int code = httpConnection.getResponseCode();

            if (code == 200)
                return true;
        } else {
            System.err.println("error - not a http request!");
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.wisdombud.right.client.common.HttpKit.java

private static int readResponseCode(HttpURLConnection conn) {
    try {//from   w w  w  . j ava 2 s .  c  om
        return conn.getResponseCode();
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return 404;
}

From source file:Main.java

public static Bitmap downLoadBitmap(String httpUrl) {
    InputStream inputStream = null;
    try {//from www.j a  v  a 2 s .com
        URL url = new URL(httpUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            return bitmap;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static void validateConnectionAfterUpload(final HttpURLConnection connection) throws IOException {

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        try (final InputStream is = connection.getInputStream()) {
            while (is.read() > 0) {
                // consume
            }// w  w  w  . jav  a  2  s .c om
        }
    } else {
        try (final InputStream is = connection.getErrorStream()) {
            final String error = IOUtils.toString(is);
            throw new IOException(String.format("Unable to upload file. Got error %d %s: %s", responseCode,
                    connection.getResponseMessage(), error));
        }
    }
    connection.disconnect();
}

From source file:com.adrguides.utils.HTTPUtils.java

public static InputStream openAddress(Context context, URL url) throws IOException {
    if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) {
        return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15
    } else {//from   w  ww  . j av a 2s  .  c om
        URLConnection urlconn = url.openConnection();
        urlconn.setReadTimeout(10000 /* milliseconds */);
        urlconn.setConnectTimeout(15000 /* milliseconds */);
        urlconn.setAllowUserInteraction(false);
        urlconn.setDoInput(true);
        urlconn.setDoOutput(false);
        if (urlconn instanceof HttpURLConnection) {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responsecode = connection.getResponseCode();
            if (responsecode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Http response code returned:" + responsecode);
            }
        }
        return urlconn.getInputStream();
    }
}

From source file:com.michelin.cio.hudson.plugins.qc.QualityCenterUtils.java

/**
 * Checks the Quality Center server URL.
 *//*  w  w w.  j a  va 2  s.c  om*/
public static FormValidation checkQcServerURL(String value, Boolean acceptEmpty) {
    String url;
    // Path to the page to check if the server is alive
    String page = "servlet/tdservlet/TDAPI_GeneralWebTreatment";

    // Do will allow empty value?
    if (StringUtils.isBlank(value)) {
        if (!acceptEmpty) {
            return FormValidation.error(Messages.QualityCenter_ServerURLMustBeDefined());
        } else {
            return FormValidation.ok();
        }
    }

    // Does the URL ends with a "/" ? if not, add it
    if (value.lastIndexOf("/") == value.length() - 1) {
        url = value + page;
    } else {
        url = value + "/" + page;
    }

    // Open the connection and perform a HEAD request
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("HEAD");

        // Check the response code
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return FormValidation.error(connection.getResponseMessage());
        }
    } catch (MalformedURLException ex) {
        // This is not a valid URL
        return FormValidation.error(Messages.QualityCenter_MalformedServerURL());
    } catch (IOException ex) {
        // Cant open connection to the server
        return FormValidation.error(Messages.QualityCenter_ErrorOpeningServerConnection());
    }

    return FormValidation.ok();
}

From source file:Main.java

static String validGet(URL url) throws IOException {
    String html = "";
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    // TODO ensure HttpsURLConnection.setDefaultSSLSocketFactory isn't
    // required to be reset like hostnames are
    HttpURLConnection conn = null;
    try {/*w  ww.j av  a 2s  .  c om*/
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        setBasicAuthentication(conn, url);
        int status = conn.getResponseCode();
        if (status != 200) {
            Logd(TAG, "Failed to get from server, returned code: " + status);
            throw new IOException("Get failed with error code " + status);
        } else {
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String decodedString;
            while ((decodedString = br.readLine()) != null) {
                html += decodedString;
            }
            in.close();
        }
    } catch (IOException e) {
        Logd(TAG, "Failed to get from server: " + e.getMessage());
    }
    if (conn != null) {
        conn.disconnect();
    }
    return html;
}