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:xyz.karpador.godfishbot.commands.GofCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    if (params == null)
        return new CommandResult(getUsage() + "\n" + getDescription());
    CommandResult result = new CommandResult();
    try {//w  ww .j a va2 s  .  c  o m
        String urlString = "https://gifbase.com/tag/" + params + "?format=json";
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setConnectTimeout(4000);
        if (con.getResponseCode() == HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder httpResult = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                httpResult.append(line);
            JSONObject resultJson = new JSONObject(httpResult.toString());
            int pageCount = resultJson.optInt("page_count", 1);
            if (pageCount > 1) {
                int page = Main.Random.nextInt(pageCount - 1) + 1;
                if (page != resultJson.getInt("page_current")) {
                    urlString += "&p=" + page;
                    url = new URL(urlString);
                    con = (HttpsURLConnection) url.openConnection();
                    con.setConnectTimeout(4000);
                    if (con.getResponseCode() == HTTP_OK) {
                        br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        httpResult.setLength(0);
                        while ((line = br.readLine()) != null)
                            httpResult.append(line);
                        resultJson = new JSONObject(httpResult.toString());
                    }
                }
            }
            JSONArray gifs = resultJson.optJSONArray("gifs");
            if (gifs != null) {
                JSONObject gif = gifs.getJSONObject(Main.Random.nextInt(gifs.length()));
                result.imageUrl = gif.getString("url");
            } else
                return null;
        } else {
            return new CommandResult("gifbase.com responded with error code: " + con.getResponseCode() + ": "
                    + con.getResponseMessage());
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
    if (result.imageUrl == null)
        return null;
    result.isGIF = true;
    return result;
}

From source file:hudson.plugins.boundary.Boundary.java

public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
    final HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("fingerprintFields", Arrays.asList("build name"));

    final Map<String, String> source = new HashMap<String, String>();
    String hostname = "localhost";

    try {//w ww.j  a  v  a  2s  . c  o  m
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        listener.getLogger().println("host lookup exception: " + e);
    }

    source.put("ref", hostname);
    source.put("type", "jenkins");
    event.put("source", source);

    final Map<String, String> properties = new HashMap<String, String>();
    properties.put("build status", build.getResult().toString());
    properties.put("build number", build.getDisplayName());
    properties.put("build name", build.getProject().getName());
    event.put("properties", properties);

    event.put("title",
            String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName()));

    if (Result.SUCCESS.equals(build.getResult())) {
        event.put("severity", "INFO");
        event.put("status", "CLOSED");
    } else {
        event.put("severity", "WARN");
        event.put("status", "OPEN");
    }

    final String url = String.format("https://api.boundary.com/%s/events", this.id);
    final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false));
    conn.setRequestProperty("Authorization", authHeader);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    InputStream is = null;
    OutputStream os = null;
    try {
        os = conn.getOutputStream();
        OBJECT_MAPPER.writeValue(os, event);
        os.flush();
        is = conn.getInputStream();
    } finally {
        close(is);
        close(os);
    }

    final int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode);
    } else {
        String location = conn.getHeaderField("Location");
        if (location.startsWith("http:")) {
            location = "https" + location.substring(4);
        }
        listener.getLogger().println("Created Boundary Event: " + location);
    }
}

From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command./*from   ww  w. j  a va 2s. c o  m*/
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

/**
 * ??HTTPS GET/*from  ww  w .java  2s  .  c o  m*/
 * 
 * @param url URL
 * @return 
 */
public static HttpResp doHttpsGet(URL url) {

    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    Reader reader = null;

    try {
        // ???httphttps
        String protocol = url.getProtocol();
        if (!PROTOCOL_HTTPS.equals(protocol)) {
            throw new XinException("xin.error.url", "?https");
        }

        // 
        conn = (HttpsURLConnection) url.openConnection();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, tmArr, new SecureRandom());

        conn.setSSLSocketFactory(sc.getSocketFactory());

        // ?
        conn.setConnectTimeout(connTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        // UserAgent
        conn.setRequestProperty("User-Agent", "java-sdk");

        // ?
        conn.connect();

        // ?
        inputStream = conn.getInputStream();
        reader = new InputStreamReader(inputStream, charset);
        BufferedReader bufferReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String inputLine = "";
        while ((inputLine = bufferReader.readLine()) != null) {
            stringBuilder.append(inputLine);
            stringBuilder.append("\n");
        }

        // 
        HttpResp resp = new HttpResp();
        resp.setStatusCode(conn.getResponseCode());
        resp.setStatusPhrase(conn.getResponseMessage());
        resp.setContent(stringBuilder.toString());

        // 
        return resp;
    } catch (MalformedURLException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (IOException e) {
        throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage()));
    } catch (KeyManagementException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (NoSuchAlgorithmException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } finally {

        if (reader != null) {
            try {
                reader.close();

            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", reader");
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", ?");
            }
        }

        // 
        quietClose(conn);
    }
}

From source file:org.wso2.carbon.sample.service.EventsManagerService.java

public String performPostCall(String requestURL, Map<String, String> postDataParams)
        throws HttpException, IOException {

    URL url;//from  w  w  w. ja  v  a 2  s .  c  om
    String response = "";

    url = new URL(requestURL);

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

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(postDataParams));

    writer.flush();
    writer.close();
    os.close();
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "";
        throw new HttpException(responseCode + "");
    }

    return response;
}

From source file:io.fabric8.apiman.BearerTokenFilter.java

/**
 * Validates the bearer token with the kubernetes oapi and returns the username
 * if it is a valid token./* ww w .ja v  a2 s.c  om*/
 * 
 * @param bearerHeader
 * @return username of the user to whom the token was issued to
 * @throws IOException - when the token is invalid, or oapi cannot be reached.
 */
protected String validateBearerToken(String bearerHeader) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    HttpsURLConnection con = (HttpsURLConnection) kubernetesOsapiUrl.openConnection();
    con.setRequestProperty("Authorization", bearerHeader);
    con.setConnectTimeout(10000);
    con.setReadTimeout(10000);
    con.setRequestProperty("Content-Type", "application/json");
    if (kubernetesTrustCert)
        TrustEverythingSSLTrustManager.trustAllSSLCertificates(con);
    con.connect();
    OAuthClientAuthorizationList userList = mapper.readValue(con.getInputStream(),
            OAuthClientAuthorizationList.class);
    String userName = userList.getItems().get(0).getMetadata().getName();
    return userName;
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * /*from   ww  w. j a  va  2s  .c om*/
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:com.nadmm.airports.notams.NotamService.java

private void fetchNotams(String icaoCode, File notamFile) throws IOException {
    String params = String.format(NOTAM_PARAM, icaoCode);

    HttpsURLConnection conn = (HttpsURLConnection) NOTAM_URL.openConnection();
    conn.setRequestProperty("Connection", "close");
    conn.setDoInput(true);//from  w  w w .  j a  v a2 s .c  o  m
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(30 * 1000);
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US)");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(params.length()));

    // Write out the form parameters as the request body
    OutputStream faa = conn.getOutputStream();
    faa.write(params.getBytes("UTF-8"));
    faa.close();

    int response = conn.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
        // Request was successful, parse the html to extract notams
        InputStream in = conn.getInputStream();
        ArrayList<String> notams = parseNotamsFromHtml(in);
        in.close();

        // Write the NOTAMS to the cache file
        BufferedOutputStream cache = new BufferedOutputStream(new FileOutputStream(notamFile));
        for (String notam : notams) {
            cache.write(notam.getBytes());
            cache.write('\n');
        }
        cache.close();
    }
}

From source file:online.privacy.PrivacyOnlineApiRequest.java

private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload)
        throws IOException, JSONException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String apiUrl = "https://api.privacy.online";
    String apiKey = this.context.getString(R.string.privacy_online_api_key);
    String keyString = "?key=" + apiKey;

    int payloadSize = jsonPayload.length();

    try {/*from w  w w.  j a  va 2 s. c o  m*/
        URL url = new URL(apiUrl + endPoint + keyString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // Sec 5 second connect/read timeouts
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (payloadSize > 0) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(payloadSize);
        }

        // Initiate the connection
        connection.connect();

        // Write the payload if there is one.
        if (payloadSize > 0) {
            outputStream = connection.getOutputStream();
            outputStream.write(jsonPayload.getBytes("UTF-8"));
        }

        // Get the response code ...
        int responseCode = connection.getResponseCode();
        Log.e(LOG_TAG, "Response code: " + responseCode);

        switch (responseCode) {
        case HttpsURLConnection.HTTP_OK:
            inputStream = connection.getInputStream();
            break;
        case HttpsURLConnection.HTTP_FORBIDDEN:
            inputStream = connection.getErrorStream();
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            inputStream = connection.getErrorStream();
            break;
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            inputStream = connection.getErrorStream();
            break;
        default:
            inputStream = connection.getInputStream();
            break;
        }

        String responseContent = "{}"; // Default to an empty object.
        if (inputStream != null) {
            responseContent = readInputStream(inputStream, connection.getContentLength());
        }

        JSONObject responseObject = new JSONObject(responseContent);
        responseObject.put("code", responseCode);

        return responseObject;

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

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

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from  ww  w . jav a2  s .c om*/
    HttpsURLConnection webRequest = null;

    this.accessToken = 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("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.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();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}