Example usage for android.net Network openConnection

List of usage examples for android.net Network openConnection

Introduction

In this page you can find the example usage for android.net Network openConnection.

Prototype

public URLConnection openConnection(URL url) throws IOException 

Source Link

Document

Opens the specified URL on this Network , such that all traffic will be sent on this Network.

Usage

From source file:Main.java

/**
 * Given a string url, connects and returns response code
 *
 * @param urlString       string to fetch
 * @param network       network/*from   w  w  w  .java 2 s .c  o m*/
 * @param readTimeOutMs       read time out
 * @param connectionTimeOutMs       connection time out
 * @param urlRedirect       should use urlRedirect
 * @param useCaches       should use cache
 * @return httpResponseCode http response code
 * @throws IOException
 */

@TargetApi(LOLLIPOP)
public static int checkUrlWithOptionsOverNetwork(String urlString, Network network, int readTimeOutMs,
        int connectionTimeOutMs, boolean urlRedirect, boolean useCaches) throws IOException {
    if (network == null) {
        return -1;
    }
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) network.openConnection(url);
    connection.setReadTimeout(readTimeOutMs /* milliseconds */);
    connection.setConnectTimeout(connectionTimeOutMs /* milliseconds */);
    connection.setRequestMethod("GET");
    connection.setInstanceFollowRedirects(urlRedirect);
    connection.setUseCaches(useCaches);
    // Starts the query
    connection.connect();
    int responseCode = connection.getResponseCode();
    connection.disconnect();
    return responseCode;
}