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

/**
 * This method checks if the Network available on the device or not.
 * //from ww  w .  j a  v a2 s.c  o  m
 * @param context
 * @return true if network available, false otherwise
 */
public static Boolean isNetworkAvailable(Context context) {
    boolean connected = false;
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        connected = true;
    } else if (netInfo != null && netInfo.isConnected() && cm.getActiveNetworkInfo().isAvailable()) {
        connected = true;
    } else if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                connected = true;
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (cm != null) {
        final NetworkInfo[] netInfoAll = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfoAll) {
            System.out.println("get network type :::" + ni.getTypeName());
            if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    && ni.isConnected() && ni.isAvailable()) {
                connected = true;
                if (connected) {
                    break;
                }
            }
        }
    }
    return connected;
}

From source file:test.LocationCrawler.java

private static String ProcessLocationRequest(String QueryItem) {
    try {// w w w.j a  v  a2s  .c  o  m
        QueryItem = URLEncoder.encode(QueryItem, "ISO-8859-1");
        String URLStr = String.format(
                "https://maps.googleapis.com/maps/api/geocode/json?" + "address=%s&sensor=false&key=%s",
                QueryItem,
                //"AIzaSyAOkEu7MBxUj4t2pBq1GZ-0Td7cf7bOKTg");
                //"AIzaSyCvzTx408371P7CtoXN8BejAAmBa0NUZbc");
                "AIzaSyAIyQ3XaHrC9TQVMIs65IrwzREtnzqZRKw");
        URL url = new URL(URLStr);

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

        if (connection.getResponseCode() == 200) {
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String sb = "";
            String str;

            while ((str = br.readLine()) != null) {
                sb += (str);
            }

            br.close();

            return sb;
        } else {
            return "";
        }
    } catch (Exception e) {
        return "";
    }
}

From source file:Main.java

@SuppressWarnings("unused")
public static void selectServer2() {
    for (String host : host_arr) {
        HttpURLConnection conn = null;
        try {/*from  w  w w  . j a  v a2s  . co  m*/
            conn = (HttpURLConnection) new URL(host).openConnection();
            conn.setConnectTimeout(6000);
            int result = conn.getResponseCode();
            String re = conn.getResponseMessage();
            if (result == HttpURLConnection.HTTP_OK) {
                HOST = host;//
                break;
            } else {
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

    }
}

From source file:Main.java

public static String loadImageFromUrl(Context context, String imageURL, File file) {
    try {/* ww w .j av a2  s.c  o m*/
        URL url = new URL(imageURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);
        con.setDoInput(true);
        con.connect();
        if (con.getResponseCode() == 200) {
            InputStream inputStream = con.getInputStream();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 20];
            int length = -1;
            while ((length = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
            byteArrayOutputStream.close();
            inputStream.close();

            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
            return file.getPath();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:Main.java

public static boolean selectServer() {
    boolean status = false;
    for (String host : host_arr) {
        String str = host + Servlet_phone;
        HttpURLConnection conn = null;
        try {//w ww . j  a v a  2 s .co  m
            conn = (HttpURLConnection) new URL(str).openConnection();
            conn.setConnectTimeout(4000);
            int result = conn.getResponseCode();
            if (result == HttpURLConnection.HTTP_OK) {
                HOST = str;//
                HOST_PORT = host;
                status = true;
                break;
            } else {
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
    }
    return status;
}

From source file:Main.java

public static String getJsonWithPath(String path) {
    StringBuffer sb = new StringBuffer();
    URL url = null;/*  w  w w  . jav a  2s  .  c o m*/
    HttpURLConnection conn = null;
    BufferedReader br = null;

    try {
        url = new URL(path);
        conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
        } else {
            Log.e(TAG, " NET IS ERROR");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(br);
        conn.disconnect();
    }
    Log.i("TAG", "---" + sb.toString());
    return sb.toString();
}

From source file:GetURLInfo.java

/** Use the URLConnection class to get info about the URL */
public static void printinfo(URL url) throws IOException {
    URLConnection c = url.openConnection(); // Get URLConnection from URL
    c.connect(); // Open a connection to URL

    // Display some information about the URL contents
    System.out.println("  Content Type: " + c.getContentType());
    System.out.println("  Content Encoding: " + c.getContentEncoding());
    System.out.println("  Content Length: " + c.getContentLength());
    System.out.println("  Date: " + new Date(c.getDate()));
    System.out.println("  Last Modified: " + new Date(c.getLastModified()));
    System.out.println("  Expiration: " + new Date(c.getExpiration()));

    // If it is an HTTP connection, display some additional information.
    if (c instanceof HttpURLConnection) {
        HttpURLConnection h = (HttpURLConnection) c;
        System.out.println("  Request Method: " + h.getRequestMethod());
        System.out.println("  Response Message: " + h.getResponseMessage());
        System.out.println("  Response Code: " + h.getResponseCode());
    }/*from w ww. j ava2 s .  c  o m*/
}

From source file:Main.java

public static boolean isAvailable(String urlString) throws IOException {
    try {/*from   www. j  a  v  a 2s  .  c o m*/
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        URL url = new URL(urlString);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000);
        urlc.connect();

        if (urlc.getResponseCode() == 200) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.baidu.api.client.core.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @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.
 *//*www . ja  va2 s  . c o m*/
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize) {
    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.";
            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();
                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.";
                    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.";
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        throw new ClientInternalException(msg);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            // ?
            System.out.println("Exception while close url - " + e.getMessage());
        }
    }
}

From source file:com.gabrielluz.megasenaanalyzer.MegaSenaAnalyzer.java

public static byte[] downloadFile(String fileUrl) throws IOException {
    java.net.CookieManager cm;/*  w w  w  .  j ava2  s.  co m*/
    cm = new java.net.CookieManager();
    java.net.CookieHandler.setDefault(cm);
    URL url = new URL(fileUrl);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        try (InputStream inputStream = httpConn.getInputStream()) {
            return MegaSenaAnalyzer.unZipIt(inputStream);
        }
    } else {
        System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        httpConn.disconnect();
        return null;
    }
}