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:Main.java

public static synchronized boolean isConnect(String url) {
    URL urlStr;/* w w  w .j  a v a 2s .c  o  m*/
    HttpURLConnection connection;
    if (url == null || url.length() <= 0) {
        return false;
    }
    try {
        urlStr = new URL(url);
        connection = (HttpURLConnection) urlStr.openConnection();
        int state = connection.getResponseCode();
        if (state == 200) {
            return true;
        }
    } catch (Exception ex) {
        return false;
    }
    return false;
}

From source file:com.microsoft.webapp.util.WebAppUtils.java

public static void sendGet(String sitePath) throws Exception {
    URL url = new URL(sitePath);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "AzureToolkit for Eclipse");
    con.getResponseCode();
}

From source file:com.vaguehope.onosendai.util.HttpHelper.java

private static String summariseHttpErrorResponse(final HttpURLConnection connection) throws IOException {
    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_NOT_FOUND)
        return String.format("HTTP %s %s", responseCode, connection.getResponseMessage());
    return String.format("HTTP %s %s: %s", responseCode, connection.getResponseMessage(),
            IoHelper.toString(connection.getErrorStream(), MAX_ERR_BODY_LENGTH_CHAR));
}

From source file:org.wisdom.framework.vertx.VertxBaseTest.java

public static void waitForStart(WisdomVertxServer server) throws InterruptedException, IOException {
    int attempt = 0;
    while (server.httpPort() == 0 && attempt < 10) {
        Thread.sleep(1000);//www . j  a v a2s.co m
        attempt++;
    }
    if (server.httpPort() == 0) {
        throw new IllegalStateException("Server not started after " + attempt + " attempts");
    }

    // No one is publishing /ping, so we are expected to get a 404.
    // Before we was trying on / but test are expecting parameters.
    URL url = new URL("http://localhost:" + server.httpPort() + "/ping");
    attempt = 0;
    int code = 0;
    while (code == 0 && attempt < 10) {
        try {
            Thread.sleep(1000);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            code = connection.getResponseCode();
            if (code != 0) {
                System.out.println("Server started (code: " + code + ")");
            }
        } catch (IOException e) {
            // Next try...
        }
        attempt++;
    }

    if (code == 0) {
        throw new IllegalStateException("Server not ready after " + attempt + " attempts");
    }
}

From source file:Main.java

/**
 * Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in
 * the 200-399 range./*from   ww w .j  av  a 2s.c  om*/
 * @param url The HTTP URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
 * given timeout, otherwise <code>false</code>.
 */
public static boolean ping(String url, int timeout) {
    // Otherwise an exception may be thrown on invalid SSL certificates:
    url = url.replaceFirst("^https", "http");

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}

From source file:com.francelabs.datafari.utils.SendHttpRequest.java

public static void sendGET(String url, String userAgent) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", userAgent);
    int responseCode = con.getResponseCode();
    logger.debug("GET Response Code :: " + responseCode);
    if (responseCode == HttpURLConnection.HTTP_OK) { // success
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;/*from   w w w .  j  a va  2  s . com*/
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        logger.debug(response.toString());
    } else {
        logger.debug("GET request not worked");
    }
}

From source file:Main.java

private static String httpGet(String address) {
    InputStream inputStream = null;
    HttpURLConnection httpURLConnection = null;
    try {//from  ww w. ja v  a2s. c  o  m
        URL url = new URL(address);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpURLConnection.getInputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            StringBuffer stringBuffer = new StringBuffer();
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuffer.append(new String(buffer, 0, len));
            }
            return stringBuffer.toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(inputStream);
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }

    }

    return null;

}

From source file:Main.java

static public String downloadFile(String downloadUrl, String fileName, String dir) throws IOException {
    URL url = new URL(downloadUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);/*from  w w  w . j  a  va2s .  c  om*/
    urlConnection.connect();
    int code = urlConnection.getResponseCode();
    if (code > 300 || code == -1) {
        throw new IOException("Cannot read url: " + downloadUrl);
    }
    String filePath = prepareFilePath(fileName, dir);
    String tmpFilePath = prepareTmpFilePath(fileName, dir);
    FileOutputStream fileOutput = new FileOutputStream(tmpFilePath);
    BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
    byte[] buffer = new byte[1024];
    int bufferLength;
    while ((bufferLength = inputStream.read(buffer)) > 0) {
        fileOutput.write(buffer, 0, bufferLength);
    }
    fileOutput.close();
    // move tmp to destination
    copyFile(new File(tmpFilePath), new File(filePath));
    return filePath;
}

From source file:Main.java

public static boolean deleteRequest(String query) {
    HttpURLConnection connection = null;
    try {// www  .  ja  v a 2s  .  c  om
        connection = (HttpURLConnection) new URL(url + query).openConnection();
        connection.setRequestMethod("DELETE");
        connection.setRequestProperty("Accept-Charset", charset);

        statusCode = connection.getResponseCode();
        if (statusCode != 200) {
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:Main.java

public static String requestData(String address) throws Exception {
    URL url = new URL(address);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(5000);// w  w w. j ava2 s .c o m
    connection.setReadTimeout(5000);
    String data = null;
    InputStream is = null;
    if (connection.getResponseCode() == 200) {
        is = connection.getInputStream();
        data = readFromStream(is);
    }
    if (is != null) {
        is.close();
    }
    return data;
}