List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java
private static URL waitForDependency(URL url, String serviceName, String key, String value, String username, String password) throws InterruptedException { boolean isFoundRunningService = false; ObjectMapper mapper = new ObjectMapper(); int counter = 0; URL endpoint = null;/*from w w w .j a v a2 s . c o m*/ while (!isFoundRunningService) { endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort())); if (endpoint != null) { String isLive = null; try { URL statusURL = new URL(endpoint.toExternalForm() + url.getPath()); HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection(); urlConnection.setConnectTimeout(500); if (urlConnection instanceof HttpsURLConnection) { try { KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH, TRUSTSTORE_PASSWORD_PATH); TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo); KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH, CLIENT_KEYSTORE_PASSWORD_PATH); KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo); final SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kms, tms, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier()); httpsConnection.setSSLSocketFactory(socketFactory); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } if (Utils.isNotNullOrEmpty(username)) { String encoded = Base64.getEncoder() .encodeToString((username + ":" + password).getBytes("UTF-8")); log.info(username + ":******"); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); } isLive = IOUtils.toString(urlConnection.getInputStream()); Map<String, Object> esResponse = mapper.readValue(isLive, new TypeReference<Map<String, Object>>() { }); if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) { isFoundRunningService = true; } else { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")" + isLive); } } catch (Exception e) { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")" + e.getMessage()); } } else { if (counter % 10 == 0) log.info("Could not find " + serviceName + " in namespace, waiting.."); } counter++; Thread.sleep(1000l); } return endpoint; }
From source file:com.mytwitter.Network.NetworkHelper.java
/** * Verifies that the handset is connected to the Internet. * * @return//from ww w . j ava 2s . c om */ public static boolean connectedToInternet(Context context) throws IOException { if (!connectedToNetwork(getConnectivityManager(context))) return false; URL googleUrl = new URL(WEBADDRESS_GOOGLE_COM_URL); HttpURLConnection connection = (HttpURLConnection) googleUrl.openConnection(); connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpStatus.SC_OK) return true; return false; /** * Alternative way (NOT TESTED): * boolean result = false; URL url; HttpURLConnection connection = null; try { url = new URL(WEBADDRESS_ANDROID_COM_URL); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(NETWORK_CONNECTION_CONNECT_TIMEOUT); connection.setReadTimeout(NETWORK_CONNECTION_READ_TIMEOUT); InetAddress address = InetAddress.getByName(WEBADDRESS_ANDROID_COM_IP); result = address.isReachable(NETWORK_CONNECTION_CONNECT_TIMEOUT); // Redirect check is valid only after the response headers have been received // InputStream in = new BufferedInputStream(connection.getInputStream()); // if (url.getHost().equals(connection.getURL().getHost())) // result = true; } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return result; */ }
From source file:localSPs.SpiderOakAPI.java
public static String connectWithREST(String url, String method) throws IOException, ProtocolException, MalformedURLException { String newURL = ""; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Connect with a REST Method: GET, DELETE, PUT con.setRequestMethod(method);/*from w w w .j a v a 2 s . c om*/ //add request header con.setReadTimeout(20000); con.setConnectTimeout(20000); con.setRequestProperty("User-Agent", "Mozilla/5.0"); if (method.equals(DELETE) || method.equals(PUT)) con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW"); int responseCode = con.getResponseCode(); // Read response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); newURL = response.toString(); return newURL; }
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String getDataFromUrl(String url) { try {// www . ja v a 2s . co m HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Unable to get data for URL " + url); } byte[] b = new byte[2048]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataInputStream d = new DataInputStream((FilterInputStream) conn.getContent()); int c = 0; while ((c = d.read(b, 0, b.length)) != -1) bos.write(b, 0, c); String return_ = new String(bos.toByteArray(), Charsets.UTF_8); logger.info("Calling URL API: {} returns: {}", url, return_); conn.disconnect(); return return_; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;//from ww w. j a va 2 s .c om try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != HttpStatus.SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java
/** * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses. * * @param destination URL of the OCSP response provider * @return list of OCSP response objects * @throws IOException if I/O errors occurred * @throws OCSPException if the response could not be parsed *///w w w . j a v a 2s .c o m public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException { HttpURLConnection connection = (HttpURLConnection) destination.openConnection(); connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED); connection.setDoOutput(true); connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout()); connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout()); connection.setRequestMethod(METHOD); connection.connect(); if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) { log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(), connection.getResponseMessage()); throw new IOException(connection.getResponseMessage()); } MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build(); final List<OCSPResp> responses = new ArrayList<>(); final MimeStreamParser parser = new MimeStreamParser(config); parser.setContentHandler(new AbstractContentHandler() { @Override public void startMultipart(BodyDescriptor bd) { parser.setFlat(); } @Override public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException { if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) { responses.add(new OCSPResp(IOUtils.toByteArray(is))); } } }); try { parser.parse(connection.getInputStream()); } catch (MimeException e) { throw new OCSPException("Error parsing response", e); } return responses; }
From source file:Main.java
public static String doGet(String urlStr) { URL url = null;/*from w w w. ja va 2 s. c om*/ HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:com.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;/* www . j a v a 2s .c om*/ try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }
From source file:Main.java
public static byte[] doGet(String urlStr) { URL url = null;/*from ww w . j av a2s. c om*/ HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toByteArray(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:com.consumerkarma.TTS.SpeechAuth.java
/** * Sets up an OAuth client credentials authentication. * Follow this with a call to fetchTo() to actually load the data. * @param oauthService the URL of the OAuth client credentials service * @param apiKey the OAuth client ID/*from w w w. ja va 2 s . c om*/ * @param apiSecret the OAuth client secret * @throws IllegalArgumentException for bad URL, etc. **/ public static SpeechAuth forService(String oauthService, String apiKey, String apiSecret) throws IllegalArgumentException { try { URL url = new URL(oauthService); HttpURLConnection request = (HttpURLConnection) url.openConnection(); String data = String.format(Locale.US, OAUTH_DATA, apiKey, apiSecret); byte[] bytes = data.getBytes("UTF8"); request.setConnectTimeout(CONNECT_TIMEOUT); request.setReadTimeout(READ_TIMEOUT); return new SpeechAuth(request, bytes); } catch (IOException e) { throw new IllegalArgumentException(e); } catch (ClassCastException e) { throw new IllegalArgumentException("URL must be HTTP: " + oauthService, e); } }