Example usage for java.net HttpURLConnection setConnectTimeout

List of usage examples for java.net HttpURLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setConnectTimeout.

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

static String fetchPlainText(URL url) throws IOException {
    InputStream in = null;/*from w  w w .j  a  v a2  s.  co m*/

    try {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = client.open(url);
        conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
        conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
        in = conn.getInputStream();
        return readFullyPlainText(in);

    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.book.jtm.chap03.HttpClientDemo.java

public static void sendRequest(String method, String url) throws IOException {
    InputStream is = null;// w  w w  . j  av a  2  s .  c  om
    try {
        URL newUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection();
        // ?10
        conn.setReadTimeout(10000);
        // 15
        conn.setConnectTimeout(15000);
        // ?,GET"GET",post"POST"
        conn.setRequestMethod("GET");
        // ??
        conn.setDoInput(true);
        // ??,????
        conn.setDoOutput(true);
        // Header
        conn.setRequestProperty("Connection", "Keep-Alive");
        // ?
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsList.add(new BasicNameValuePair("username", "mr.simple"));
        paramsList.add(new BasicNameValuePair("pwd", "mypwd"));
        writeParams(conn.getOutputStream(), paramsList);

        // ?
        conn.connect();
        is = conn.getInputStream();
        // ?
        String result = convertStreamToString(is);
        Log.i("", "###  : " + result);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.samsung.msf.youtubeplayer.client.util.FeedParser.java

/**
 * Given a string representation of a URL, sets up a connection and gets an input stream.
 *///from w w w.jav a 2  s .com
public static InputStream downloadUrl(final URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
    conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

From source file:com.zimbra.common.util.ngxlookup.ZimbraNginxLookUpClient.java

/**
 * Pings a HTTP(S) URL. This effectively sends a GET request and returns <code>true</code> if the response code is 200
 * @param url The HTTP(S) URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout.
 * @return <code>true</code> if the given HTTP(S) URL has returned response code 200 within the
 * given timeout, otherwise <code>false</code>.
 */// ww w  .j  a  v a 2s .  c o m
public static boolean ping(String url, int timeout) {
    ZimbraLog.misc.debug("attempting to ping \"%s\" with timeout %d", url, timeout);
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        return (connection.getResponseCode() == 200) ? true : false;
    } catch (IOException exception) {
        return false;
    }
}

From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java

public static String getAuthToken(String server, String code) {

    String token = null;//from ww  w  . jav  a2 s.c om

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_CODE, code));
    params.add(new BasicNameValuePair(PARAM_CLIENT_SECRET, CLIENT_SECRET));

    InputStream is = null;
    URL auth_token_url;
    try {
        auth_token_url = getRequestURL(server, PATH_OAUTH_ACCESS_TOKEN, params);
        Log.i(TAG, auth_token_url.toString());

        HttpURLConnection conn = (HttpURLConnection) auth_token_url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response_code = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response_code);
        is = conn.getInputStream();

        // parse token_response as JSON to get the token out
        String str_response = readStreamToString(is, 500);
        Log.d(TAG, str_response);
        JSONObject response = new JSONObject(str_response);
        token = response.getString("access_token");

    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Log.i(TAG, token);
    return token;
}

From source file:com.vinexs.tool.NetworkManager.java

public static void haveInternet(Context context, final OnInternetResponseListener listener) {
    if (!haveNetwork(context)) {
        listener.onResponsed(false);//from   ww  w .  j a  va  2 s  .  co  m
        return;
    }
    Log.d("Network", "Check internet is reachable ...");
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InetAddress ipAddr = InetAddress.getByName("google.com");
                if (ipAddr.toString().equals("")) {
                    throw new Exception("Cannot resolve host name, no internet behind network.");
                }
                HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(3500);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
                postOutputStream.write('\n');
                postOutputStream.close();
                conn.disconnect();
                Log.d("Network", "Internet is reachable.");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Network", "Internet is unreachable.");
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            listener.onResponsed(result);
        }
    }.execute();
}

From source file:com.blogspot.ryanfx.auth.GoogleUtil.java

/**
 * Sends the auth token to google and gets the json result.
 * @param token auth token// www.j av  a2 s .co m
 * @return json result if valid request, null if invalid.
 * @throws IOException
 * @throws LoginException
 */
private static String issueTokenGetRequest(String token) throws IOException, LoginException {
    int timeout = 2000;
    URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setRequestProperty("Authorization", "OAuth " + token);
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();
    if (status == HttpServletResponse.SC_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();
    } else if (status == HttpServletResponse.SC_UNAUTHORIZED) {
        Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token);
    }
    return null;
}

From source file:com.mk4droid.IMC_Services.Download_Data.java

/**
 * Download Image from a certain url/*  ww  w  .  j  a  v  a 2 s  . c om*/
 * 
 * @param fullPath the url of the image
 * @return
 */
public static byte[] Down_Image(String fullPath) {

    try {
        //----- Split----
        String[] AllInfo = fullPath.split("/");

        // Encode filename as UTF8 -------
        String fnExt = AllInfo[AllInfo.length - 1];

        String fnExt_UTF8 = URLEncoder.encode(fnExt, "UTF-8");

        //- Replace new fn to old
        AllInfo[AllInfo.length - 1] = fnExt_UTF8;

        //------ Concatenate to a single string -----
        String newfullPath = AllInfo[0];
        for (int i = 1; i < AllInfo.length; i++)
            newfullPath += "/" + AllInfo[i];

        // empty space becomes + after UTF8, then replace with %20
        newfullPath = newfullPath.replace("+", "%20");

        //------------ Download -------------
        URL myFileUrl = new URL(newfullPath);

        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.setConnectTimeout(10000);
        conn.connect();
        InputStream isBitmap = conn.getInputStream();
        return readBytes(isBitmap);

    } catch (Exception e) {
        Log.e(Constants_API.TAG, "Download_Data: Down_Image: Error in http connection " + e.getMessage());
        return null;
    }

}

From source file:com.att.ads.sample.SpeechAuth.java

/**
 * Sets up an OAuth client credentials authentication.
 * Follow this with a call to fetchTo() to actually load the data.
 * @param oauthService the URL of the OAuth client credentials service
 * @param apiKey the OAuth client ID/*www  .j  a  v  a  2s .co  m*/
 * @param apiSecret the OAuth client secret
 * @throws IllegalArgumentException for bad URL, etc.
**/
public static SpeechAuth forService(String oauthService, String oauthScope, String apiKey, String apiSecret)
        throws IllegalArgumentException {
    try {
        URL url = new URL(oauthService);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        String data = String.format(Locale.US, OAUTH_DATA, oauthScope, apiKey, apiSecret);
        byte[] bytes = data.getBytes("UTF8");
        request.setConnectTimeout(CONNECT_TIMEOUT);
        request.setReadTimeout(READ_TIMEOUT);
        return new SpeechAuth(request, bytes);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("URL must be HTTP: " + oauthService, e);
    }
}

From source file:Main.java

public static void downloadImage(String imageUrl) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.d("TAG", "monted sdcard");
    } else {//from  w  w w  .jav a  2  s  . co  m
        Log.d("TAG", "has no sdcard");
    }
    HttpURLConnection con = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    File imageFile = null;
    try {
        URL url = new URL(imageUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);
        con.setReadTimeout(15 * 1000);
        con.setDoInput(true);
        con.setDoOutput(true);
        bis = new BufferedInputStream(con.getInputStream());
        imageFile = new File(getImagePath(imageUrl));
        fos = new FileOutputStream(imageFile);
        bos = new BufferedOutputStream(fos);
        byte[] b = new byte[1024];
        int length;
        while ((length = bis.read(b)) != -1) {
            bos.write(b, 0, length);
            bos.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (con != null) {
                con.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (imageFile != null) {
    }
}