Example usage for javax.net.ssl HttpsURLConnection setConnectTimeout

List of usage examples for javax.net.ssl HttpsURLConnection setConnectTimeout

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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:org.openhab.binding.neato.internal.VendorVorwerk.java

@Override
public String executeRequest(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout) throws IOException {

    URL requestUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();
    applyNucleoSslConfiguration(connection);
    connection.setRequestMethod(httpMethod);
    for (String propName : httpHeaders.stringPropertyNames()) {
        connection.addRequestProperty(propName, httpHeaders.getProperty(propName));
    }//from  ww w  . ja  v a2 s.  c o m
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    content.reset();
    IOUtils.copy(content, connection.getOutputStream());

    java.io.InputStream is = connection.getInputStream();
    return IOUtils.toString(is);
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;// w w  w.j  ava2  s  .  c  om
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:org.kontalk.client.ClientHTTPConnection.java

private void setupClient(HttpsURLConnection conn, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoInput(true);/*from w  w w . j  a  v a  2 s  .c o  m*/
    conn.setSSLSocketFactory(setupSSLSocketFactory(mContext, mPrivateKey, mCertificate, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code HttpsURLConnection} from the given
 * {@code context} and {@code hostnameVerifier}.
 * /*from ww w  .  j  av a2s.c o m*/
 * @param context
 *            the TrustManagerFactory to get the SSLContext
 * @return the new {@code HttpsURLConnection} instance.
 * @throws IOException
 *             if an error occurs while opening the connection.
 */
private HttpsURLConnection getURLConnection(SSLContext context, HostnameVerifier hostnameVerifier)
        throws IOException {

    URL url = new URL("https://10.0.2.2/mycode/digitalSig.php");

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setConnectTimeout(3000);
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setHostnameVerifier(hostnameVerifier);

    return urlConnection;
}

From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java

private ArrayList<LatLng> fetchPlacesFromAPI(LatLng center, int radius) {
    ArrayList<LatLng> places = new ArrayList<>();
    radius = Math.min(radius, 50000); // Max accepted radius is 50km.

    try {/*from   ww w .  j  a v  a  2  s .c  o  m*/
        InputStream is = null;
        URL url = new URL(getString(R.string.places_api_url) + "?location=" + center.latitude + ","
                + center.longitude + "&radius=" + radius);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        // Pass package name and signature as part of request
        String packageName = getPackageName();
        String signature = getAppSignature();

        conn.setRequestProperty("X-App-Package", packageName);
        conn.setRequestProperty("X-App-Signature", signature);

        conn.connect();
        int response = conn.getResponseCode();
        if (response != 200) {
            Log.e(TAG, "Places API HTTP error: " + response + " / " + url);
        } else {
            BufferedReader reader;
            StringBuilder builder = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            for (String line; (line = reader.readLine()) != null;) {
                builder.append(line);
            }
            JSONArray resultsJson = (new JSONObject(builder.toString())).getJSONArray("results");
            for (int i = 0; i < resultsJson.length(); i++) {
                JSONObject latLngJson = ((JSONObject) resultsJson.get(i)).getJSONObject("geometry")
                        .getJSONObject("location");
                places.add(new LatLng(latLngJson.getDouble("lat"), latLngJson.getDouble("lng")));
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception parsing places API: " + e.toString());
    }

    return places;
}

From source file:com.gloriouseggroll.LastFMAPI.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;//from   w  w w .ja  va  2s .co  m
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Exception " + j.getString("_exception")
                + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData HTTP/Available " + j.getInt("_http") + "("
                + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout)
        throws IOException {
    String correctedRequest = request;
    if (StringUtils.isNotBlank(correctedRequest)) {
        correctedRequest = fixRequest(correctedRequest);
        URL url = new URL(this.uri + correctedRequest);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        if (connection != null) {
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            if (sslSocketFactory != null) {
                connection.setSSLSocketFactory(sslSocketFactory);
            }//from  w  w  w . j a v  a  2  s.com
            if (hostnameVerifier != null) {
                connection.setHostnameVerifier(hostnameVerifier);
            }
        }
        return connection;
    }
    return null;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {//from w  ww . j  av a2 s. c om
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

        return new String[] { code + "", result };
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callPostAndPut " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callPostAndPut " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:com.gmt2001.TwitchAPIv2.java

private JSONObject GetData(request_type type, String url, String post, String oauth) {
    JSONObject j = new JSONObject();

    try {//from   ww  w  .j av  a  2  s.c om
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);

        c.connect();

        if (!post.isEmpty()) {
            IOUtils.write(post, c.getOutputStream());
        }

        String content;

        if (c.getResponseCode() == 200) {
            content = IOUtils.toString(c.getInputStream(), c.getContentEncoding());
        } else {
            content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding());
        }

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
    }

    return j;
}

From source file:com.carvoyant.modularinput.Program.java

private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) {
    JSONObject tokenJson = null;//w w w.  ja v a2s .  c o m
    HttpsURLConnection getTokenConnection = null;

    try {
        BufferedReader tokenResponseReader = null;
        URL url = new URL("https://api.carvoyant.com/oauth/token");
        //         URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token");
        getTokenConnection = (HttpsURLConnection) url.openConnection();
        getTokenConnection.setReadTimeout(30000);
        getTokenConnection.setConnectTimeout(30000);
        getTokenConnection.setRequestMethod("POST");
        getTokenConnection.setDoInput(true);
        getTokenConnection.setDoOutput(true);

        List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>();
        getTokenParams.add(new SimpleEntry("client_id", clientId));
        getTokenParams.add(new SimpleEntry("client_secret", clientSecret));
        getTokenParams.add(new SimpleEntry("grant_type", "refresh_token"));
        getTokenParams.add(new SimpleEntry("refresh_token", refreshToken));

        String userpass = clientId + ":" + clientSecret;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        getTokenConnection.setRequestProperty("Authorization", basicAuth);

        OutputStream os = getTokenConnection.getOutputStream();
        os.write(getQuery(getTokenParams).getBytes("UTF-8"));
        os.close();

        if (getTokenConnection.getResponseCode() < 400) {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getInputStream()));
            String inputLine;
            StringBuffer sb = new StringBuffer();
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }

            tokenJson = new JSONObject(sb.toString());
            ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token.");
        } else {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }
            ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId
                    + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString());
        }

        getTokenConnection.disconnect();
    } catch (MalformedURLException mue) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage());
    } catch (IOException ioe) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage());
    } finally {
        if (null != getTokenConnection) {
            getTokenConnection.disconnect();
        }
    }

    return tokenJson;
}