List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java
private HttpURLConnection createUrlConnection(String url) throws IOException { URL newURL = new URL(url); URLConnection urlConnection = newURL.openConnection(); urlConnection.setConnectTimeout(mConfig.connTimeOut); urlConnection.setReadTimeout(mConfig.soTimeOut); urlConnection.setDoInput(true);//from w w w.j a v a 2 s . co m urlConnection.setUseCaches(false); return (HttpURLConnection) urlConnection; }
From source file:com.netflix.iep.dynprop.RemoteConfigurationSource.java
private Properties getProperties() throws IOException { AbstractConfiguration config = ConfigurationManager.getConfigInstance(); String vip = config.getString(VIP, "atlas_archaius-main:7001"); List<String> hosts = getHostsForVip(vip, config.getBoolean(USE_IP, false)); int numAttempts = config.getInt(NUM_RETRIES, 2) + 1; for (int i = 1; i <= numAttempts; ++i) { String host = hosts.get(i % hosts.size()); String url = "http://" + host + "/api/v1/property" + "?asg=" + getAsgName() + "&instanceId=" + getInstanceId() + "&zone=" + getZone(); logger.debug("attempt {} of {}, requesting properties from: {}", i, numAttempts, url); try {//ww w . j a v a2 s. c om URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(config.getInt(CONNECT_TIMEOUT, 1000)); con.setReadTimeout(config.getInt(READ_TIMEOUT, 5000)); Properties props = new Properties(); try (InputStream in = con.getInputStream()) { props.load(in); } logger.debug("fetched {} properties from: {}", props.size(), url); return props; } catch (IOException e) { String msg = String.format("attempt %d of %d failed, url: %s", i, numAttempts, url); if (i == numAttempts) { logger.error(msg, e); throw e; } else { logger.warn(msg, e); } } } // Shouldn't get here throw new IllegalStateException("failed to get properties"); }
From source file:org.jesterj.ingest.processors.FetchUrl.java
@Override public Document[] processDocument(Document document) { URL url = null;//from w w w.ja v a2 s . c o m try { url = new URL(document.getFirstValue(linkField)); String protocol = url.getProtocol(); String server = url.getHost(); Long lastAccess = visitedSiteCache.getIfPresent(server); long now = System.currentTimeMillis(); if (lastAccess == null) { visitedSiteCache.put(server, now); } else { long elapsed = now - lastAccess; if (elapsed < throttleMs) { try { Thread.sleep(throttleMs - elapsed); } catch (InterruptedException e) { // ignore, not really important. } } } URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (protocol != null && ("http".equals(protocol) || "https".equals(protocol))) { HttpURLConnection httpConnection = (HttpURLConnection) conn; int responseCode = httpConnection.getResponseCode(); if (httpStatusField != null) { document.put(httpStatusField, String.valueOf(responseCode)); } if (responseCode >= 400) { String message = "HTTP server responded " + responseCode + " " + httpConnection.getResponseMessage(); if (errorField != null) { document.put(errorField, message); } throw new IOException(message); } } IOUtils.copy(conn.getInputStream(), baos); document.setRawData(baos.toByteArray()); } catch (IOException e) { if (failOnIOError) { if (errorField != null) { document.put(errorField, e.getMessage()); } document.setStatus(Status.ERROR); } else { log.warn("Could not fetch " + url + " for " + document.getId(), e); } } return new Document[] { document }; }
From source file:org.b5chat.crossfire.web.FaviconServlet.java
private byte[] getImage(String url) { try {//www . j ava 2s. c o m // Try to get the fiveicon from the url using an HTTP connection from the pool // that also allows to configure timeout values (e.g. connect and get data) GetMethod get = new GetMethod(url); get.setFollowRedirects(true); int response = client.executeMethod(get); if (response < 400) { // Check that the response was successful. Should we also filter 30* code? return get.getResponseBody(); } else { // Remote server returned an error so return null return null; } } catch (IllegalStateException e) { // Something failed (probably a method not supported) so try the old stye now try { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setReadTimeout(1000); urlConnection.connect(); DataInputStream di = new DataInputStream(urlConnection.getInputStream()); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteStream); int len; byte[] b = new byte[1024]; while ((len = di.read(b)) != -1) { out.write(b, 0, len); } di.close(); out.flush(); return byteStream.toByteArray(); } catch (IOException ioe) { // We failed again so return null return null; } } catch (IOException ioe) { // We failed so return null return null; } }
From source file:org.dlut.mycloudserver.service.performancemonitor.PerformanceListener.java
private void monitorForOne(PerformanceMonitorDTO performanceMonitorDTO) { String url = "http://" + performanceMonitorDTO.getIp() + ":8001"; InputStream is = null;//from w w w . j a v a 2 s. c om BufferedReader br = null; try { URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(CONN_TIME_OUT); conn.setReadTimeout(READ_TIME_OUT); is = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String res = br.readLine(); br.close(); is.close(); JSONObject jsonRes = JSON.parseObject(res); int cores = jsonRes.getIntValue("cores"); int totalMem = jsonRes.getIntValue("totalMem"); int usedMem = jsonRes.getIntValue("usedMem"); double loadAverage = jsonRes.getDoubleValue("loadAverage"); double sendRate = jsonRes.getDoubleValue("sendRate"); double receiveRate = jsonRes.getDoubleValue("receiveRate"); performanceMonitorDTO.setPerformanceMonitorStatus(PerformanceMonitorStatusEnum.RUNNING); performanceMonitorDTO.setCores(cores); performanceMonitorDTO.setTotalMem(totalMem); performanceMonitorDTO.setUsedMem(usedMem); performanceMonitorDTO.setLoadAverage(loadAverage); performanceMonitorDTO.setSendRate(sendRate); performanceMonitorDTO.setReceiveRate(receiveRate); } catch (IOException e) { log.warn("" + performanceMonitorDTO.getIp() + " "); performanceMonitorDTO.setPerformanceMonitorStatus(PerformanceMonitorStatusEnum.CLOSED); } finally { if (br != null) { try { br.close(); } catch (IOException e) { log.error("error message", e); } } if (is != null) { try { is.close(); } catch (IOException e) { log.error("error message", e); } } } // ?? MyCloudResult<Boolean> res = performanceMonitorService.updatePerformanceMonitor(performanceMonitorDTO); if (!res.isSuccess()) { log.error("?" + res.getMsgInfo()); } }
From source file:com.github.beat.signer.pdf_signer.TSAClient.java
private byte[] getTSAResponse(byte[] request) throws IOException { LOGGER.debug("Opening connection to TSA server"); // FIXME: support proxy servers URLConnection connection = tsaInfo.getTsaUrl().openConnection(); connection.setDoOutput(true);//from w ww .ja v a 2 s. c om connection.setDoInput(true); connection.setReadTimeout(CONNECT_TIMEOUT); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setRequestProperty("Content-Type", "application/timestamp-query"); // TODO set accept header LOGGER.debug("Established connection to TSA server"); String username = tsaInfo.getUsername(); char[] password = tsaInfo.getPassword(); if (StringUtils.isNotBlank(username) && password != null) { // FIXME this most likely wrong, e.g. set correct request property! // connection.setRequestProperty(username, password); } // read response sendRequest(request, connection); LOGGER.debug("Waiting for response from TSA server"); byte[] response = getResponse(connection); LOGGER.debug("Received response from TSA server"); return response; }
From source file:com.google.bazel.example.android.activities.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_ping) { new AsyncTask<String, Void, String>() { public static final int READ_TIMEOUT_MS = 5000; public static final int CONNECTION_TIMEOUT_MS = 2000; private String inputStreamToString(InputStream stream) throws IOException { StringBuilder result = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line;/*ww w .j ava 2s .c om*/ while ((line = reader.readLine()) != null) { result.append(line); } } finally { stream.close(); } return result.toString(); } private HttpURLConnection getConnection(String url) throws IOException { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_MS); urlConnection.setReadTimeout(READ_TIMEOUT_MS); return (HttpURLConnection) urlConnection; } @Override protected String doInBackground(String... params) { String url = params[0]; HttpURLConnection connection = null; try { connection = getConnection(url); return new JSONObject(inputStreamToString(connection.getInputStream())) .getString("requested"); } catch (IOException e) { Log.e("background", "IOException", e); return null; } catch (JSONException e) { Log.e("background", "JSONException", e); return null; } finally { if (connection != null) { connection.disconnect(); } } } @Override protected void onPostExecute(String result) { TextView textView = (TextView) findViewById(R.id.text_view); if (result == null) { Toast.makeText(MainActivity.this, getString(R.string.error_sending_request), Toast.LENGTH_LONG).show(); textView.setText("???"); return; } textView.setText(result); } }.execute("http://10.0.2.2:8080/boop"); return true; } return super.onOptionsItemSelected(item); }
From source file:org.shredzone.commons.gravatar.impl.GravatarServiceImpl.java
/** * Fetches a Gravatar icon from the server and stores it in the given {@link File}. * * @param url/*from ww w . j a v a 2 s .c o m*/ * Gravatar URL to fetch * @param file * {@link File} to store the icon to */ private void fetchGravatar(URL url, File file) throws IOException { limitUpstreamRequests(); URLConnection conn = url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (file.exists()) { conn.setIfModifiedSince(file.lastModified()); } conn.connect(); long lastModified = conn.getLastModified(); if (lastModified > 0L && lastModified <= file.lastModified()) { // Cache file exists and is unchanged if (log.isDebugEnabled()) { log.debug("Cached Gravatar is still good: {}", url); } file.setLastModified(System.currentTimeMillis()); // touch return; } try (InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(file)) { byte[] buffer = new byte[8192]; int total = 0; int len; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); total += len; if (total > MAX_GRAVATAR_SIZE) { log.warn("Gravatar exceeded maximum size: {}", url); break; } } out.flush(); if (log.isDebugEnabled()) { log.debug("Downloaded Gravatar: {}", url); } } }
From source file:org.tupelo_schneck.electric.ted.ImportIterator.java
public ImportIterator(final Options options, final byte mtu, final int count) throws IOException { this.timeZone = options.recordTimeZone; this.cal = new GregorianCalendar(this.timeZone); this.mtu = mtu; this.useVoltage = options.voltage; URL url;/* w w w . j ava 2s .c o m*/ try { url = new URL( options.gatewayURL + "/history/rawsecondhistory.raw?INDEX=1&MTU=" + mtu + "&COUNT=" + count); } catch (MalformedURLException e) { throw new RuntimeException(e); } URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(60000); urlConnection.setReadTimeout(60000); urlConnection.connect(); urlStream = urlConnection.getInputStream(); urlConnection.setReadTimeout(1000); getNextLine(); // skip the first timestamp, in case we see only part of multiple values if (!closed) { Triple first = nextFromLine(); Triple next = first; while (next != null && next.timestamp == first.timestamp) { next = nextFromLine(); } pushback = next; if (Util.inDSTOverlap(timeZone, first.timestamp)) { int now = (int) (System.currentTimeMillis() / 1000); if (now < first.timestamp - 1800) inDSTOverlap = 1; else inDSTOverlap = 2; } previousTimestamp = first.timestamp; } }
From source file:com.adito.extensions.store.ExtensionStoreDescriptor.java
private void loadDocument() throws IOException, JDOMException { URLConnection conx = descriptor.openConnection(); conx.setConnectTimeout(ExtensionStore.CONNECT_TIMEOUT); conx.setReadTimeout(ExtensionStore.READ_TIMEOUT); InputStream in = null;/* w w w . ja v a2 s. c o m*/ try { in = conx.getInputStream(); SAXBuilder sax = new SAXBuilder(); document = sax.build(in); if (!document.getRootElement().getName().equalsIgnoreCase("applications")) { throw new JDOMException("Application root element must be <applications>"); } store = document.getRootElement().getAttribute("store").getValue(); if (store == null) { throw new JDOMException("<applications> element requires attribute 'store'"); } } finally { Util.closeStream(in); } }