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

static public String download_json(String url_addr) {
    StringBuilder result = new StringBuilder();
    try {//from  w  ww. j av a2 s .  c  o  m
        URL url = new URL(url_addr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn != null) {
            conn.setConnectTimeout(10000);
            conn.setUseCaches(false);
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                for (;;) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    result.append(line + '\n');
                }
                br.close();
            } else {
                conn.disconnect();
                return null;
            }
            conn.disconnect();
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return null;
    }
    return result.toString();
}

From source file:com.melchor629.musicote.Utils.java

/**
 * HostTest/*from w ww  .j  av  a 2 s.c o  m*/
 * Sirve para comprobar si est encendido el PC
 * Nothing to see here...
 *
 * @param host HOST IP
 * @return int response
 */
public static int HostTest(String host) {
    int response = 0;

    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        URL urlhttp = new URL("http://" + host);
        HttpURLConnection http = (HttpURLConnection) urlhttp.openConnection();
        http.setReadTimeout(1000);
        response = http.getResponseCode();
        http.disconnect();
    } catch (Exception e) {
        Log.e("Comprobando", "Excepcin HTTPURL: " + e.toString() + " " + host);
    }

    return response;
}

From source file:OCRRestAPI.java

private static void DownloadConvertedFile(String outputFileUrl) throws IOException {
    URL downloadUrl = new URL(outputFileUrl);
    HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection();

    if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

        InputStream inputStream = downloadConnection.getInputStream();

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc");

        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }/*from   ww  w .  j  a va 2  s  . c  om*/

        outputStream.close();
        inputStream.close();
    }

    downloadConnection.disconnect();
}

From source file:commonUtils.CommonUtils.java

public static boolean IsExistsLink(String inputLink) {
    try {/* w  w w . j a va 2s  .c  o m*/
        URL url = new URL(inputLink);
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("GET");
        huc.connect();
        System.out.println(huc.getResponseCode());
        if (huc.getResponseCode() == 200) {
            return true;
        }

    } catch (Exception ex) {
        return false;
    }
    return false;
}

From source file:com.telefonica.iot.perseo.test.Help.java

public static Res doMethod(String url, String method) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(method);/*  w w  w  .  j av a 2  s.c o m*/
    int responseCode = con.getResponseCode();
    String body = getBodyResponse(con);
    return new Res(responseCode, body);
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

private static void verifyResponseCode(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException("Invalid http response code from responder: " + connection.getResponseCode());
    }/*w  w  w.j  ava2s . c o m*/
}

From source file:Main.java

public static String getJsonContent(String url_path) {
    try {/*  w  ww.  j a  v  a 2 s  .c  o m*/
        URL url = new URL(url_path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        int code = connection.getResponseCode();
        if (code == 200) {
            return changeInputStream(connection.getInputStream());
        }
    } catch (Exception e) {

    }
    return "";
}

From source file:com.example.prathik1.drfarm.OCRRestAPI.java

private static void DownloadConvertedFile(String outputFileUrl) throws IOException {
        URL downloadUrl = new URL(outputFileUrl);
        HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection();

        if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

            InputStream inputStream = downloadConnection.getInputStream();

            // opens an output stream to save into file
            FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc");

            int bytesRead = -1;
            byte[] buffer = new byte[4096];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }/* w  w  w. j  a va 2  s .co m*/

            outputStream.close();
            inputStream.close();
        }

        downloadConnection.disconnect();
    }

From source file:com.pkrete.locationservice.admin.util.WebUtil.java

/**
 * Checks if the given URL exists./*from   w  w  w.  ja  v  a  2  s . c o  m*/
 *
 * @param url the URL to be checked
 * @return if the URL is exists returns true, otherwise returns false
 */
public static boolean exists(String url) {
    try {
        HttpURLConnection.setFollowRedirects(true);
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        // HTTP statuses 200 and 302 are accepted
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK
                || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

From source file:com.iwgame.iwcloud.baidu.task.util.DownloadUtil.java

/**
 * url/*  w  w w  .j a  va2 s  .co  m*/
 * @param strUrl
 *            The Url to be downloaded.
 * @param connectTimeout
 *            Connect timeout in milliseconds.
 * @param readTimeout
 *            Read timeout in milliseconds.
 * @param maxFileSize
 *            Max file size in BYTE.
 * @return The file content as byte array.
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize)
        throws IOException {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                logger.error(msg);
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    logger.error(msg);
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        logger.error(msg);
        throw e;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("Exception while close url - ", e);
            throw e;
        }
    }
}