List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:de.jetwick.util.Translate.java
public static String download(String urlAsString) { try {/*from w w w . j a v a 2s .com*/ URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); hConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"); hConn.addRequestProperty("Referer", "http://jetsli.de/crawler"); hConn.setConnectTimeout(2000); hConn.setReadTimeout(2000); InputStream is = hConn.getInputStream(); if ("gzip".equals(hConn.getContentEncoding())) is = new GZIPInputStream(is); return getInputStream(is); } catch (Exception ex) { return ""; } }
From source file:io.fabric8.apiman.ApimanStarter.java
private static URL waitForDependency(URL url, String path, 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 ww w . j ava 2 s. co 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() + path); HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection(); urlConnection.setConnectTimeout(500); if (urlConnection instanceof HttpsURLConnection) { try { KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH, ApimanStarter.TRUSTSTORE_PASSWORD_PATH); TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo); KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info( ApimanStarter.CLIENT_KEYSTORE_PATH, ApimanStarter.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")); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); log.info(username + ":" + "*****"); } 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. " + isLive); } } catch (Exception e) { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. " + 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:Main.java
public static String callJsonAPI(String urlString) { // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient HttpURLConnection urlConnection = null; StringBuilder jsonResult = new StringBuilder(); try {//w w w .j a v a 2s .c o m URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(TIMEOUT_CONNECTION); urlConnection.setReadTimeout(TIMEOUT_READ); urlConnection.connect(); int status = urlConnection.getResponseCode(); switch (status) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = br.readLine()) != null) { jsonResult.append(line).append("\n"); } br.close(); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); return e.getMessage(); } catch (IOException e) { System.err.print(e.getMessage()); return e.getMessage(); } finally { if (urlConnection != null) { try { urlConnection.disconnect(); } catch (Exception e) { System.err.print(e.getMessage()); } } } return jsonResult.toString(); }
From source file:net.line2soft.preambul.utils.Network.java
/** * Checks if a connection is possible between device and server. * @param address The URL to request/*from w w w.java 2 s .c o m*/ * @return True if the connection is possible, false else */ public static boolean checkConnection(URL address) { boolean result = false; try { HttpURLConnection urlc = (HttpURLConnection) address.openConnection(); //urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); urlc.connect(); if (urlc.getResponseCode() == 200) { result = true; } } catch (Exception e) { ; } return result; }
From source file:dictinsight.utils.io.HttpUtils.java
public static String getDataFromOtherServer(String url) { String rec = null;/*from w w w .j a v a 2 s. c om*/ BufferedReader reader = null; HttpURLConnection connection = null; try { URL srcUrl = new URL(url); connection = (HttpURLConnection) srcUrl.openConnection(); connection.setConnectTimeout(1000 * 10); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); rec = reader.readLine(); } catch (Exception e) { System.out.println("get date from " + url + " error!"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) connection.disconnect(); } return rec; }
From source file:com.example.android.didyoufeelit.Utils.java
/** * Make an HTTP request to the given URL and return a String as the response. *//*from w w w .j a v a 2 s. c om*/ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; }
From source file:ee.ria.xroad.proxy.ProxyMain.java
private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() { Map<String, DiagnosticsStatus> statuses = new HashMap<>(); for (String tspUrl : ServerConf.getTspUrl()) { try {/*ww w . j a v a 2 s . c om*/ URL url = new URL(tspUrl); log.info("Checking timestamp server status for url {}", url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS); con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/timestamp-query"); con.connect(); log.info("Checking timestamp server con {}", con); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok", con.getResponseCode(), con.getResponseMessage()); statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl)); } else { statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl)); } } catch (Exception e) { log.warn("Timestamp status check failed {}", e); statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl)); } } return statuses; }
From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}.//from ww w . ja va 2 s. c o m * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. * @author Sections of this code contributed by jTribe (http://jtribe.com.au) */ protected static synchronized String getUrlContent(String sUrl, String email, String pword) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } String userPassword = email + ":" + pword; String encoding = Base64Coder.encodeString(userPassword); try { URL url = new URL(sUrl); System.setProperty("http.keepAlive", "false"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setRequestProperty("User-Agent", sUserAgent); connection.setRequestMethod("GET"); //Get response code int responseCode = connection.getResponseCode(); if (responseCode != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + connection.getResponseMessage()); } // Pull content stream from response InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
From source file:de.Keyle.MyPet.api.Util.java
public static String readUrlContent(String address, int timeout) throws IOException { StringBuilder contents = new StringBuilder(2048); BufferedReader br = null;/*from w ww . j av a2s . c om*/ try { URL url = new URL(address); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout); huc.setRequestMethod("GET"); huc.connect(); br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String line; while ((line = br.readLine()) != null) { contents.append(line); } } finally { try { if (br != null) { br.close(); } } catch (Exception e) { e.printStackTrace(); } } return contents.toString(); }
From source file:chen.android.toolkit.network.HttpConnection.java
/** * </br><b>title : </b> ????POST?? * </br><b>description :</b>????POST?? * </br><b>time :</b> 2012-7-8 ?4:34:08 * @param method ??/*from ww w . j a v a 2 s .c o m*/ * @param url POSTURL * @param datas ???? * @return ??? * @throws IOException */ private static InputStream connect(String method, URL url, byte[]... datas) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setConnectTimeout(6 * 1000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); OutputStream outputStream = conn.getOutputStream(); for (byte[] data : datas) { outputStream.write(data); } outputStream.close(); return conn.getInputStream(); }