List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:oneDrive.OneDriveAPI.java
public static String connectWithREST(String url, String method) throws IOException, ProtocolException { String newURL = ""; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Connect with a REST Method: GET, DELETE, PUT con.setRequestMethod(method);/*from www .jav a 2 s . c o m*/ //add request header con.setReadTimeout(20000); con.setConnectTimeout(20000); con.setRequestProperty("User-Agent", "Mozilla/5.0"); if (method.equals(DELETE) || method.equals(PUT) || getSize) con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN); 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.polyvi.xface.http.XHttpWorker.java
/** * url???/*from w w w.j av a 2s .c o m*/ * * @param url * [in] * @return */ public static boolean isServerAccessable(String url) { boolean usable = false; try { URL urlCon = new URL(url); HttpURLConnection httpUrl = (HttpURLConnection) urlCon.openConnection(); httpUrl.setConnectTimeout(SERVER_CONNECT_TIMEOUT); httpUrl.setReadTimeout(SERVER_CONNECT_TIMEOUT); if (httpUrl.getResponseCode() == HttpURLConnection.HTTP_OK) { usable = true; return usable; } } catch (IOException e) { usable = false; e.printStackTrace(); } return usable; }
From source file:ee.ria.xroad.signer.certmanager.OcspClient.java
private static HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(MimeUtils.HEADER_CONTENT_TYPE, MimeTypes.OCSP_REQUEST); connection.setRequestProperty("Accept", MimeTypes.OCSP_RESPONSE); connection.setDoOutput(true);/*w w w. j a v a2s. c om*/ connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); connection.connect(); return connection; }
From source file:org.pixmob.fm2.util.HttpUtils.java
/** * Create a new Http connection for an URI. *//*from w w w . j a v a 2 s .c o m*/ public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies) throws IOException { if (DEBUG) { Log.d(TAG, "Setup connection to " + uri); } final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(30000); conn.setReadTimeout(60000); conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setRequestProperty("User-Agent", getUserAgent(context)); conn.setRequestProperty("Cache-Control", "max-age=0"); conn.setDoInput(true); // Close the connection when the request is done, or the application may // freeze due to a bug in some Android versions. conn.setRequestProperty("Connection", "close"); if (conn instanceof HttpsURLConnection) { setupSecureConnection(context, (HttpsURLConnection) conn); } if (cookies != null && !cookies.isEmpty()) { final StringBuilder buf = new StringBuilder(256); for (final String cookie : cookies) { if (buf.length() != 0) { buf.append("; "); } buf.append(cookie); } conn.addRequestProperty("Cookie", buf.toString()); } return conn; }
From source file:net.andylizi.colormotd.utils.AttributionUtil.java
private static String sendGet(String url, String param, String charset) { StringBuilder result = new StringBuilder(1024); BufferedReader in = null;//from w ww . ja v a2 s . co m try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("User-Agent", "ColorMOTD/" + UUID.randomUUID()); conn.setRequestProperty("Accept-Charset", charset); conn.setUseCaches(true); conn.setConnectTimeout(2000); conn.setReadTimeout(3000); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024); String line; while ((line = in.readLine()) != null) { result.append(line); } conn.disconnect(); } catch (Exception e) { } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { } } return result.toString(); }
From source file:Main.java
/** * On some devices we have to hack:/*from w ww. j a v a 2 s . c o m*/ * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public static String getRedirectUrl(REGION region) { String result = ""; switch (region) { case EU://w w w . j av a 2s . c o m result = amazonEuDomain; break; case USA: result = amazonUsaDomain; break; case ASIA: result = amazonAsiaDomain; break; } System.out.println("Trying to get real IP address of " + result); try { /* HttpHead headRequest = new HttpHead(result); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(headRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { String location = response.getHeaders("Location")[0].toString(); String redirecturl = location.replace("Location: ", ""); result = redirecturl; } */ URL url = new URL(result); HttpURLConnection httpGetCon = (HttpURLConnection) url.openConnection(); httpGetCon.setInstanceFollowRedirects(false); httpGetCon.setRequestMethod("GET"); httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds httpGetCon.setRequestProperty("User-Agent", USER_AGENT); int status = httpGetCon.getResponseCode(); System.out.println("code: " + status); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) result = httpGetCon.getHeaderField("Location"); } catch (Exception e) { System.out.println("Exception is fired in redirector getter. error:" + e.getMessage()); e.printStackTrace(); } System.out.println("Real IP address is " + result); return result; }
From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBlockchainInfo() { try {//www . j a v a2s .c o m Double btcRate = 0.0; Object result = getCoinValueBTC(); if (result == null) return null; else btcRate = (Double) result; final URL URL = new URL("https://blockchain.info/ticker"); final HttpURLConnection connection = (HttpURLConnection) URL.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return null; Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); 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 String rate = o.optString("15m", null); double rateForBTC = o.getDouble("15m") * btcRate; final String rate = String.format("%.8f", rateForBTC); //o.optString("15m", null); if (rate != null) { try { rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } catch (final ArithmeticException x) { log.debug("problem reading exchange rate: " + currencyCode, x); } } } return rates; } finally { if (reader != null) reader.close(); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } return null; }
From source file:net.andylizi.colormotd.anim.utils.AttributionUtil.java
private static String sendGet(String url, String param, String charset) { StringBuilder result = new StringBuilder(1024); BufferedReader in = null;/*from ww w .java 2 s .c o m*/ try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("User-Agent", Main.getInstance().getDescription().getFullName()); conn.setRequestProperty("Accept-Charset", charset); conn.setUseCaches(true); conn.setConnectTimeout(2000); conn.setReadTimeout(3000); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024); String line; while ((line = in.readLine()) != null) { result.append(line); } conn.disconnect(); } catch (Exception e) { } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { } } return result.toString(); }
From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBitcoinCharts() { try {/*from w ww. j av a2 s . c om*/ Double btcRate = 0.0; Object result = getCoinValueBTC(); if (result == null) return null; else btcRate = (Double) result; final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json"); final HttpURLConnection connection = (HttpURLConnection) URL.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return null; Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); String rate = o.optString("24h", null); if (rate == null) rate = o.optString("7d", null); if (rate == null) rate = o.optString("30d", null); double rateForBTC = Double.parseDouble(rate); rate = String.format("%.8f", rateForBTC * btcRate); if (rate != null) { try { rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } catch (final ArithmeticException x) { log.debug("problem reading exchange rate: " + currencyCode, x); } } } } return rates; } finally { if (reader != null) reader.close(); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } return null; }