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.mobiperf_library.measurements.PingTask.java

/** 
 * Use the HTTP Head method to emulate ping. The measurement from this method can be 
 * substantially (2x) greater than the first two methods and inaccurate. This is because, 
 * depending on the implementing of the destination web server, either a quick HTTP
 * response is replied or some actual heavy lifting will be done in preparing the response
 * *//*from w ww .j  a va  2 s .c o  m*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        URL url = new URL("http://" + pingTask.target);

        int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
            httpClient.setRequestProperty("Connection", "close");
            httpClient.setRequestMethod("HEAD");
            httpClient.setReadTimeout(timeOut);
            httpClient.setConnectTimeout(timeOut);
            httpClient.connect();
            pingEndTime = System.currentTimeMillis();
            httpClient.disconnect();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        Logger.i("RTT is " + rrts.toString());
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP);
    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public boolean guvnorExists() {
    String checkURLStr = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
            + "/rest/packages/";

    try {//  ww  w .  ja va2 s . c  om
        URL checkURL = new URL(checkURLStr);
        HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
        checkConnection.setRequestMethod("GET");
        checkConnection.setRequestProperty("Accept", "application/atom+xml");
        checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
        checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
        applyAuth(checkConnection);
        checkConnection.connect();
        return (checkConnection.getResponseCode() == 200);
    } catch (Exception e) {
        logger.error("Error checking guvnor existence: " + e.getMessage());
        return false;
    }
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

private HttpURLConnection setupConnection(URL url, Map<String, String> parameters) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(10_000);/*from   w w  w  .j  a v  a 2 s . com*/
    connection.setConnectTimeout(15_000);
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    OutputStream os = connection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(buildParametersList(parameters));
    writer.flush();
    writer.close();
    os.close();
    return connection;
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Configures the connection timeout values and headers.
 *//*from w  w w .  j a  va 2  s  .  c o m*/
protected void prepareConnection(HttpURLConnection connection) throws IOException {
    if (readTimeout >= 0)
        connection.setReadTimeout(readTimeout);
    if (connectTimeout >= 0)
        connection.setConnectTimeout(connectTimeout);

    if (headers != null) {
        for (String key : headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }
    }
    if (user != null) {
        String value = user + ":" + password;
        connection.setRequestProperty(HTTP_BASIC_AUTH_HEADER,
                "Basic " + new String(Base64.encodeBase64(value.getBytes())));
    }
}

From source file:com.mobiperf.measurements.PingTask.java

/** 
 * Use the HTTP Head method to emulate ping. The measurement from this method can be 
 * substantially (2x) greater than the first two methods and inaccurate. This is because, 
 * depending on the implementing of the destination web server, either a quick HTTP
 * response is replied or some actual heavy lifting will be done in preparing the response
 * *//* w ww. j ava2 s.  c o m*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        URL url = new URL("http://" + pingTask.target);

        int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
            httpClient.setRequestProperty("Connection", "close");
            httpClient.setRequestMethod("HEAD");
            httpClient.setReadTimeout(timeOut);
            httpClient.setConnectTimeout(timeOut);
            httpClient.connect();
            pingEndTime = System.currentTimeMillis();
            httpClient.disconnect();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        Logger.i("RTT is " + rrts.toString());
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP);
        dataConsumed += pingTask.packetSizeByte * Config.PING_COUNT_PER_MEASUREMENT * 2;

    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getAll(Context context) {
    // synchronized (Swingset.initPlaygroundLock) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {//from www  . j a  v a2 s  .  com
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground");
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    // all done
    Log.d(TAG, "   -> returned " + result);
    return playgrounds;
    // }
}

From source file:com.synelixis.xifi.AuthWebClient.Client.java

public String getURL(String url_, String token_) {
    URL obj;/*from w ww.j a  v a2  s .c  o m*/
    try {
        obj = new URL(url_);
        HttpURLConnection c = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        c.setRequestMethod("GET");

        //add request header
        //c.setRequestProperty("User-Agent", "Mozilla/5.0");
        //c.setRequestProperty("Content-Type", "application/json");
        //c.setRequestProperty("X-Auth-Token", token_);
        c.setRequestProperty("Authorization", "Bearer " + new String(Base64.encodeBase64(token_.getBytes())));
        c.setRequestProperty("accept", "application/json");
        c.setConnectTimeout(50000);
        int responseCode = c.getResponseCode();

        System.out.println("Response Code : " + responseCode);
        switch (c.getResponseCode()) {
        case 200:
        case 201:
            BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
    return null;
}