Example usage for java.net URLConnection setConnectTimeout

List of usage examples for java.net URLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net URLConnection 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

public static String getDataFromOtherServer(String url, String param) {
    PrintWriter out = null;//from  w  w w. jav a 2 s. c o  m
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        conn.setConnectTimeout(1000 * 10);
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        out.print(param);
        out.flush();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + param + " error!");
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:com.gallatinsystems.common.util.S3Util.java

public static URLConnection getConnection(String bucketName, String objectKey, String awsAccessKeyId,
        String awsAccessSecret) throws IOException {

    final String date = getDate();
    final String payload = String.format(GET_PAYLOAD, date, bucketName, objectKey);

    final String signature = MD5Util.generateHMAC(payload, awsAccessSecret);

    final URL url = new URL(String.format(S3_URL, bucketName, objectKey));
    final URLConnection conn = url.openConnection();

    conn.setConnectTimeout(CONNECTION_TIMEOUT);
    conn.setReadTimeout(CONNECTION_TIMEOUT);
    conn.addRequestProperty("Cache-Control", "no-cache,max-age=0");
    conn.setRequestProperty("Date", date);
    conn.setRequestProperty("Authorization", "AWS " + awsAccessKeyId + ":" + signature);

    return conn;//ww w. j ava2s.com
}

From source file:xtrememp.update.SoftwareUpdate.java

public static Version getLastVersion(URL url) throws Exception {
    Version result = null;//from   w  ww  . j a  v a 2  s .  co  m
    InputStream urlStream = null;
    try {
        URLConnection urlConnection = url.openConnection();
        urlConnection.setAllowUserInteraction(false);
        urlConnection.setConnectTimeout(30000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(false);
        urlConnection.setReadTimeout(10000);
        urlConnection.setUseCaches(true);
        urlStream = urlConnection.getInputStream();
        Properties properties = new Properties();
        properties.load(urlStream);

        result = new Version();
        result.setMajorNumber(Integer.parseInt(properties.getProperty("xtrememp.lastVersion.majorNumber")));
        result.setMinorNumber(Integer.parseInt(properties.getProperty("xtrememp.lastVersion.minorNumber")));
        result.setMicroNumber(Integer.parseInt(properties.getProperty("xtrememp.lastVersion.microNumber")));
        result.setVersionType(
                Version.VersionType.valueOf(properties.getProperty("xtrememp.lastVersion.versionType")));
        result.setReleaseDate(properties.getProperty("xtrememp.lastVersion.releaseDate"));
        result.setDownloadURL(properties.getProperty("xtrememp.lastVersion.dounloadURL"));
    } finally {
        IOUtils.closeQuietly(urlStream);
    }
    return result;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http(String s) throws SQLException, IOException {

    String resp = "";
    final URL url = new URL(s);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(60000);
    connection.setReadTimeout(60000);//from ww  w. j av a  2s  .  com
    connection.addRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
    connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
    while (reader.hasNextLine()) {
        final String line = reader.nextLine();
        resp += line + "\n";
    }
    reader.close();

    return resp;
}

From source file:ninja.standalone.NinjaJettyTest.java

static public String get(String url) throws Exception {
    URL u = new URL(url);
    URLConnection conn = u.openConnection();
    conn.setAllowUserInteraction(false);
    conn.setConnectTimeout(3000);
    conn.setReadTimeout(3000);//from   w  w  w . j a  v a 2 s  .  co m

    try (InputStream is = conn.getInputStream()) {
        return IOUtils.toString(conn.getInputStream());
    }
}

From source file:org.wso2.carbon.apimgt.core.util.APIMWSDLUtils.java

/**
 * Retrieves the WSDL located in the provided URI ({@code wsdlUrl}
 *
 * @param wsdlUrl URL of the WSDL file/*w  w w  .j  av  a2  s.  c  om*/
 * @return Content bytes of the WSDL file
 * @throws APIMgtWSDLException If an error occurred while retrieving the WSDL file
 */
public static byte[] getWSDL(String wsdlUrl) throws APIMgtWSDLException {
    ByteArrayOutputStream outputStream = null;
    InputStream inputStream = null;
    URLConnection conn;
    try {
        URL url = new URL(wsdlUrl);
        conn = url.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        conn.connect();

        outputStream = new ByteArrayOutputStream();
        inputStream = conn.getInputStream();
        IOUtils.copy(inputStream, outputStream);
        return outputStream.toByteArray();
    } catch (IOException e) {
        throw new APIMgtWSDLException("Error while reading content from " + wsdlUrl, e,
                ExceptionCodes.INVALID_WSDL_URL_EXCEPTION);
    } finally {
        if (outputStream != null) {
            IOUtils.closeQuietly(outputStream);
        }
        if (inputStream != null) {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

From source file:com.evilisn.DAO.CertMapper.java

static void setTimeout(URLConnection conn) {

    conn.setConnectTimeout(10 * 1000);

    conn.setReadTimeout(10 * 1000);

}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Double getLycBtcRate() {
    try {/*from www .j av a2  s  .  c om*/
        final URL URL = new URL("http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=177");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final JSONObject head = new JSONObject(content.toString());
            final JSONObject o = head.getJSONObject("return").getJSONObject("markets").getJSONObject("LYC");
            final Double rate = o.getDouble("lasttradeprice");
            if (rate != null)
                return rate;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {//from w w  w  .  j ava2  s  . c o  m
        final URL URL = new URL("https://blockchain.info/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                final Double drate = o.getDouble("15m") * LycBtcRate;
                String rate = String.format("%.8f", drate);
                rate = rate.replace(",", ".");
                if (rate != null)
                    rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate),
                            "cryptsy.com and " + URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:net.technicpack.launchercore.restful.RestObject.java

public static <T extends RestObject> T getRestObject(Class<T> restObject, String url)
        throws RestfulAPIException {
    InputStream stream = null;//from   w ww . j ava 2 s.  co  m
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        String data = IOUtils.toString(stream);
        T result = gson.fromJson(data, restObject);

        if (result == null) {
            throw new RestfulAPIException("Unable to access URL [" + url + "]");
        }

        if (result.hasError()) {
            throw new RestfulAPIException("Error in response: " + result.getError());
        }

        return result;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e);
    } catch (MalformedURLException e) {
        throw new RestfulAPIException("Invalid URL [" + url + "]", e);
    } catch (JsonParseException e) {
        throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + url + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}