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:dictinsight.utils.io.HttpUtils.java

/**
 * https??post//from w  w  w.  j av  a2 s. co m
 * @param url
 * @param param
 * @return post?
 */
public static String httpsPostData(String url, String param) {
    class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    BufferedOutputStream brOutStream = null;
    BufferedReader reader = null;

    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();
        connection.setSSLSocketFactory(context.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(1000 * 15);

        brOutStream = new BufferedOutputStream(connection.getOutputStream());
        brOutStream.write(param.getBytes());
        brOutStream.flush();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseContent = "";
        String line = reader.readLine();
        while (line != null) {
            responseContent += line;
            line = reader.readLine();
        }

        return responseContent;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (brOutStream != null)
                brOutStream.close();
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

private static HttpCookie getTmCookie(final String url, final String username, final String password,
        final int timeout) throws IOException {
    if (tmCookie != null && !tmCookie.hasExpired()) {
        return tmCookie;
    }//from   w  ww . j  av a  2s  .  co  m

    final String charset = UTF8_STR;
    final String query = String.format("u=%s&p=%s", URLEncoder.encode(username, charset),
            URLEncoder.encode(password, charset));
    final URLConnection connection = new URL(url).openConnection();

    if (!(connection instanceof HttpsURLConnection)) {
        return null;
    }

    final HttpsURLConnection http = (HttpsURLConnection) connection;

    http.setInstanceFollowRedirects(false);

    http.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    });

    http.setRequestMethod("POST");
    http.setAllowUserInteraction(true);

    if (timeout != 0) {
        http.setConnectTimeout(timeout);
        http.setReadTimeout(timeout);
    }

    http.setDoOutput(true); // Triggers POST.
    http.setRequestProperty("Accept-Charset", charset);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    OutputStream output = null;

    try {
        output = http.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOGGER.debug(e, e);
            }
        }
    }

    LOGGER.info("fetching cookie: " + url);
    connection.connect();

    tmCookie = HttpCookie.parse(http.getHeaderField("Set-Cookie")).get(0);
    LOGGER.debug("cookie: " + tmCookie);

    return tmCookie;
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Get//from   ww w. j a va 2  s. c o m
 * 
 * @param url
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws KeyManagementException
 */
public static String get(String url) {//throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
    InputStream in = null;
    HttpsURLConnection http = null;

    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }
        return bufferRes.toString();
    } catch (Exception e) {
        logger.error(String.format("HTTP GET url=[%s] due to fail.", url), e);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP GET url=[%s] close inputstream due to fail.", url), e);
            }
        }
        if (http != null) {
            // 
            http.disconnect();
        }
    }

    return StringUtils.EMPTY;

}

From source file:com.daoke.mobileserver.test.TestHttps.java

public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
        throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;//from w ww . ja  v a 2 s  . c  o  m
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Post//  ww  w  .j  ava 2 s .c  o m
 * 
 * @param url
 * @param params
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    OutputStream out = null;
    InputStream in = null;
    HttpsURLConnection http = null;
    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        out = http.getOutputStream();
        out.write(params.getBytes("UTF-8"));
        out.flush();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }

        return bufferRes.toString();

    } catch (Exception e) {
        logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e);
    } finally {

        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s]  close outputstream due to fail.",
                        url, params), e);
            }
        }
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url,
                        params), e);
            }
        }

        if (http != null) {
            // 
            http.disconnect();

        }
    }
    return StringUtils.EMPTY;
}

From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
        throws IOException, HttpResultException {

    HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
    nection.setDoInput(true);/* w  ww  .ja va  2 s.  c o m*/
    nection.setDoOutput(true);
    nection.setConnectTimeout(2000);
    nection.setReadTimeout(1000);
    nection.setRequestProperty("Content-Type", "application/json");
    nection.setRequestProperty("Accept", "application/json");
    nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
    if (accessToken != null) {
        nection.setRequestProperty("Authorization", "token " + accessToken);
    }

    OutputStream os = nection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(params.toString());
    writer.flush();
    writer.close();
    os.close();

    try {

        nection.connect();

        int code = nection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) {
            throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage());
        }

        InputStream in = new BufferedInputStream(nection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder response = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            response.append(line);
        }

        try {
            return new JSONObject(response.toString());
        } catch (JSONException e) {
            throw new IOException(e);
        }

    } finally {
        nection.disconnect();
    }

}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;//from w  w w.  j  a v  a2 s  .  c  o  m
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java

private static HttpsURLConnection fetchConnection(String apiURL, int timeout, Proxy proxy)
        throws MalformedURLException, IOException, ProtocolException {
    HttpsURLConnection connection;
    URL hostURL = new URL(apiURL);
    if (proxy == null) {
        connection = (HttpsURLConnection) hostURL.openConnection();
    } else {/*from w w w.  j av  a2 s .  com*/
        connection = (HttpsURLConnection) hostURL.openConnection(proxy);
    }

    // This actually turns into a POST since we are writing to the
    // resource body. ( You can see this in Webscarab or some other HTTP
    // interceptor.
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    return connection;
}

From source file:com.voa.weixin.utils.HttpUtils.java

/**
 * httpspost?/*ww w .j  a  v a 2  s . c om*/
 * 
 * @param url
 * @param param
 * @return
 * @throws Exception
 */
private static String doHttps(String url, String param, String method) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;
    String rsp = null;
    byte[] content = param.getBytes("utf-8");
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), method, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
        } catch (Exception e) {
            throw e;
        }
        try {
            out = conn.getOutputStream();
            if (StringUtils.isNotBlank(param))
                out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.github.opengarageapp.GarageService.java

protected void setupConnectionProperties(HttpsURLConnection urlConnection) {
    urlConnection.setConnectTimeout(TIMEOUT);
}