List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.galileha.smarthome.SmartHome.java
/** * Get Command List JSON File From Server * //w ww. j ava 2 s. c o m * @throws IOException * @throws MalformedURLException * @throws JSONException */ public void getCommandsList() throws IOException, MalformedURLException, JSONException { // Connect to Intel Galileo get Commands List HttpURLConnection httpCon = (HttpURLConnection) commandsJSONUrl.openConnection(); httpCon.setReadTimeout(10000); httpCon.setConnectTimeout(15000); httpCon.setRequestMethod("GET"); httpCon.setDoInput(true); httpCon.connect(); // Read JSON File as InputStream InputStream readCommand = httpCon.getInputStream(); Scanner scanCommand = new Scanner(readCommand).useDelimiter("\\A"); // Set stream to String String commandFile = scanCommand.hasNext() ? scanCommand.next() : ""; // Initialize serveFile as read string JSONObject commandsList = new JSONObject(commandFile); JSONObject temp = (JSONObject) commandsList.get("commands"); JSONArray comArray = (JSONArray) temp.getJSONArray("command"); int numberOfCommands = comArray.length(); commands = new String[numberOfCommands]; // Fill the Array for (int i = 0; i < numberOfCommands; i++) { JSONObject commandObject = (JSONObject) comArray.get(i); commands[i] = commandObject.getString("text"); } Log.d("JSON", "Loaded " + commands[2]); httpCon.disconnect(); }
From source file:com.gaze.webpaser.StackWidgetService.java
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache // CHECK : if trying to decode file which not exist in cache return null Bitmap b = decodeFile(f);/*ww w. j a va2s .c o m*/ if (b != null) return b; // Download image file from web try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); // Constructs a new FileOutputStream that writes to file // if file not exist then it will create file OutputStream os = new FileOutputStream(f); // See Utils class CopyStream method // It will each pixel from input stream and // write pixels to output stream (file) Util.CopyStream(is, os); os.close(); conn.disconnect(); // Now file created and going to resize file with defined height // Decodes image and scales it to reduce memory consumption bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
From source file:io.webfolder.cdp.ChromiumDownloader.java
public Path download(ChromiumVersion version) { final Path destinationRoot = getChromiumPath(version); final Path executable = getExecutable(version); String url;/*w w w . j a v a2 s .co m*/ if (WINDOWS) { url = format("%s/Win_x64/%d/chrome-win.zip", DOWNLOAD_HOST, version.getRevision()); } else if (LINUX) { url = format("%s/Linux_x64/%d/chrome-linux.zip", DOWNLOAD_HOST, version.getRevision()); } else if (MAC) { url = format("%s/Mac/%d/chrome-mac.zip", DOWNLOAD_HOST, version.getRevision()); } else { throw new CdpException("Unsupported OS found - " + OS); } try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("HEAD"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (conn.getResponseCode() != 200) { throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage()); } long contentLength = conn.getHeaderFieldLong("x-goog-stored-content-length", 0); String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + "-r" + version.getRevision() + ".zip"; Path archive = get(getProperty("java.io.tmpdir")).resolve(fileName); if (exists(archive) && contentLength != size(archive)) { delete(archive); } if (!exists(archive)) { logger.info("Downloading Chromium [revision=" + version.getRevision() + "] 0%"); u = new URL(url); if (conn.getResponseCode() != 200) { throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage()); } conn = (HttpURLConnection) u.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); Thread thread = null; AtomicBoolean halt = new AtomicBoolean(false); Runnable progress = () -> { try { long fileSize = size(archive); logger.info("Downloading Chromium [revision={}] {}%", version.getRevision(), round((fileSize * 100L) / contentLength)); } catch (IOException e) { // ignore } }; try (InputStream is = conn.getInputStream()) { logger.info("Download location: " + archive.toString()); thread = new Thread(() -> { while (true) { try { if (halt.get()) { break; } progress.run(); sleep(1000); } catch (Throwable e) { // ignore } } }); thread.setName("cdp4j"); thread.setDaemon(true); thread.start(); copy(conn.getInputStream(), archive); } finally { if (thread != null) { progress.run(); halt.set(true); } } } logger.info("Extracting to: " + destinationRoot.toString()); if (exists(archive)) { createDirectories(destinationRoot); unpack(archive.toFile(), destinationRoot.toFile()); } if (!exists(executable) || !isExecutable(executable)) { throw new CdpException("Chromium executable not found: " + executable.toString()); } if (!WINDOWS) { Set<PosixFilePermission> permissions = getPosixFilePermissions(executable); if (!permissions.contains(OWNER_EXECUTE)) { permissions.add(OWNER_EXECUTE); setPosixFilePermissions(executable, permissions); } if (!permissions.contains(GROUP_EXECUTE)) { permissions.add(GROUP_EXECUTE); setPosixFilePermissions(executable, permissions); } } } catch (IOException e) { throw new CdpException(e); } return executable; }
From source file:com.amazonaws.http.UrlHttpClient.java
void configureConnection(HttpRequest request, HttpURLConnection connection) { // configure the connection connection.setConnectTimeout(config.getConnectionTimeout()); connection.setReadTimeout(config.getSocketTimeout()); // disable redirect and cache connection.setInstanceFollowRedirects(false); connection.setUseCaches(false);/*from w w w. ja va 2 s.co m*/ // is streaming if (request.isStreaming()) { connection.setChunkedStreamingMode(0); } // configure https connection if (connection instanceof HttpsURLConnection) { final HttpsURLConnection https = (HttpsURLConnection) connection; // disable cert check /* * Commented as per https://support.google.com/faqs/answer/6346016. Uncomment for testing. if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { disableCertificateValidation(https); } */ if (config.getTrustManager() != null) { enableCustomTrustManager(https); } } }
From source file:libthrift091.transport.THttpClient.java
public void flush() throws TTransportException { if (null != this.client) { flushUsingHttpClient();//w w w . j a va 2s .c om return; } // Extract request and reset buffer byte[] data = requestBuffer_.toByteArray(); requestBuffer_.reset(); try { // Create connection object HttpURLConnection connection = (HttpURLConnection) url_.openConnection(); // Timeouts, only if explicitly set if (connectTimeout_ > 0) { connection.setConnectTimeout(connectTimeout_); } if (readTimeout_ > 0) { connection.setReadTimeout(readTimeout_); } // Make the request connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-thrift"); connection.setRequestProperty("Accept", "application/x-thrift"); connection.setRequestProperty("User-Agent", "Java/THttpClient"); if (customHeaders_ != null) { for (Map.Entry<String, String> header : customHeaders_.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } } connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(data); int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new TTransportException("HTTP Response code: " + responseCode); } // Read the responses inputStream_ = connection.getInputStream(); } catch (IOException iox) { throw new TTransportException(iox); } }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
private HttpURLConnection buildConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true);//from ww w . j a va2 s . c o m connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setUseCaches(false); // Set the authorization header if one has been specified if (authorization != null) { connection.setRequestProperty("Authorization", authorization); } return connection; }
From source file:cm.aptoide.pt.util.NetworkUtils.java
public BufferedInputStream getInputStream(String url, String username, String password, Context mctx) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); if (username != null && password != null) { String basicAuth = "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP)); connection.setRequestProperty("Authorization", basicAuth); }/*from w w w . j a v a2 s . c o m*/ connection.setConnectTimeout(TIME_OUT); connection.setReadTimeout(TIME_OUT); connection.setRequestProperty("User-Agent", getUserAgentString(mctx)); System.out.println("Using user-agent: " + (getUserAgentString(mctx))); BufferedInputStream bis = new BufferedInputStream(connection.getInputStream(), 8 * 1024); // if(ApplicationAptoide.DEBUG_MODE) Log.i("Aptoide-NetworkUtils", "Getting: " + url); return bis; }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * Proxy???/*w ww .j av a 2 s .com*/ * * @param proxy * Proxy * @param url */ public static long testProxy(Proxy proxy, URL url, int ctimeout, int rtimeout, int testTimes) { if (proxy == null) return -1; if (url == null) { try { url = new URL(DEFAULT_TEST_PROXY_URL); } catch (MalformedURLException e1) { LOG.warn("[testProxy] illegal url -> {}", url); return -1; } } HttpURLConnection conn = null; try { StopWatch watch = new StopWatch(); watch.start(); conn = (HttpURLConnection) url.openConnection(proxy); if (ctimeout > 0) conn.setConnectTimeout(ctimeout); if (rtimeout > 0) conn.setReadTimeout(rtimeout); long available = conn.getInputStream().available(); // try to get input int code = conn.getResponseCode(); if (available < 1 || code != 200) return -1; //no content get watch.stop(); return watch.getTime(); } catch (Exception e) { LOG.warn("[testProxy] Could not connect to proxy -> {}", proxy.address()); if (testTimes > 0) return testProxy(proxy, url, ctimeout, rtimeout, testTimes - 1); } finally { if (conn != null) IOUtils.close(conn); } return -1; }
From source file:com.wanikani.wklib.Connection.java
private void setTimeouts(HttpURLConnection conn) { conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); }
From source file:net.servicestack.client.JsonServiceClient.java
public HttpURLConnection createRequest(String requestUrl, String httpMethod, byte[] requestBody, String requestType) {//w w w . j a va2s .c o m try { URL url = new URL(requestUrl); HttpURLConnection req = (HttpURLConnection) url.openConnection(); req.setDoOutput(true); if (timeoutMs != null) { req.setConnectTimeout(timeoutMs); req.setReadTimeout(timeoutMs); } req.setRequestMethod(httpMethod); req.setRequestProperty(HttpHeaders.Accept, MimeTypes.Json); if (requestType != null) { req.setRequestProperty(HttpHeaders.ContentType, requestType); } if (requestBody != null) { req.setRequestProperty(HttpHeaders.ContentLength, Integer.toString(requestBody.length)); DataOutputStream wr = new DataOutputStream(req.getOutputStream()); wr.write(requestBody); wr.flush(); wr.close(); } if (RequestFilter != null) { RequestFilter.exec(req); } if (GlobalRequestFilter != null) { GlobalRequestFilter.exec(req); } return req; } catch (IOException e) { throw new RuntimeException(e); } }