List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:net.mutil.util.HttpUtil.java
public static String connServerForResultPost(String strUrl, HashMap<String, String> entityMap) throws ClientProtocolException, IOException { String strResult = ""; URL url = new URL(HttpUtil.getPCURL() + strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); StringBuilder entitySb = new StringBuilder(""); Object[] entityKeys = entityMap.keySet().toArray(); for (int i = 0; i < entityKeys.length; i++) { String key = (String) entityKeys[i]; if (i == 0) { entitySb.append(key + "=" + entityMap.get(key)); } else {/* w w w.ja va 2 s . c om*/ entitySb.append("&" + key + "=" + entityMap.get(key)); } } byte[] entity = entitySb.toString().getBytes("UTF-8"); System.out.println(url.toString() + entitySb.toString()); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); conn.getOutputStream().write(entity); if (conn.getResponseCode() == 200) { InputStream inputstream = conn.getInputStream(); StringBuffer buffer = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = inputstream.read(b)) != -1;) { buffer.append(new String(b, 0, n)); } strResult = buffer.toString(); } return strResult; }
From source file:net.mceoin.cominghome.api.NestUtil.java
private static String getNestAwayStatusCall(String access_token) { String away_status = ""; String urlString = "https://developer-api.nest.com/structures?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try {/* w ww. ja va 2s . co m*/ URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(15000); // urlConnection.setChunkedStreamingMode(0); // urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // urlConnection.setChunkedStreamingMode(0); // System.out.println("Redirect to URL : " + newUrl); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; InputStream response; response = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); JSONObject structure = object.getJSONObject(key); if (structure.has("away")) { away_status = structure.getString("away"); } else { log.info("missing away"); } } } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) away_status = "Error: " + errorResult; return away_status; }
From source file:dk.kk.ibikecphlib.util.HttpUtils.java
public static JsonResult readLink(String urlString, String method, boolean breakRoute) { JsonResult result = new JsonResult(); if (urlString == null) { return result; }//from w w w. ja v a 2 s. c o m URL url = null; HttpURLConnection httpget = null; try { LOG.d("HttpUtils readlink() " + urlString); url = new URL(urlString); httpget = (HttpURLConnection) url.openConnection(); httpget.setDoInput(true); httpget.setRequestMethod(method); if (breakRoute) { httpget.setRequestProperty("Accept", "application/vnd.ibikecph.v1"); } else { httpget.setRequestProperty("Accept", "application/json"); } httpget.setConnectTimeout(CONNECTON_TIMEOUT); httpget.setReadTimeout(CONNECTON_TIMEOUT); JsonNode root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class); if (root != null) { result.setNode(root); } } catch (JsonParseException e) { LOG.w("HttpUtils readLink() JsonParseException ", e); result.error = JsonResult.ErrorCode.APIError; } catch (MalformedURLException e) { LOG.w("HttpUtils readLink() MalformedURLException", e); result.error = JsonResult.ErrorCode.APIError; } catch (FileNotFoundException e) { LOG.w("HttpUtils readLink() FileNotFoundException", e); result.error = JsonResult.ErrorCode.NotFound; } catch (IOException e) { LOG.w("HttpUtils readLink() IOException", e); result.error = JsonResult.ErrorCode.ConnectionError; } catch (Exception e) { } finally { if (httpget != null) { httpget.disconnect(); } } LOG.d("HttpUtils readLink() " + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed")); return result; }
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Object getCoinValueBTC() { Date date = new Date(); long now = date.getTime(); //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;//w w w. j ava 2s . c o m String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=" + CoinDefinition.cryptsyMarketId; HttpURLConnection connectionCryptsy = null; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); connectionCryptsy = (HttpURLConnection) URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2); connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); Io.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker); JSONArray recenttrades = coinInfo.getJSONArray("recenttrades"); double btcTraded = 0.0; double coinTraded = 0.0; for (int i = 0; i < recenttrades.length(); ++i) { JSONObject trade = (JSONObject) recenttrades.get(i); btcTraded += trade.getDouble("total"); coinTraded += trade.getDouble("quantity"); } Double averageTrade = btcTraded / coinTraded; //Double lastTrade = GLD.getDouble("lasttradeprice"); //String euros = String.format("%.7f", averageTrade); // Fix things like 3,1250 //euros = euros.replace(",", "."); //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost())); if (currencyCryptsy.equalsIgnoreCase("BTC")) btcRate = averageTrade; } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } } return btcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } finally { if (connectionCryptsy != null) connectionCryptsy.disconnect(); } return null; }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
/** * Does an HTTP post for a given form data string. * * @param data is the form data string.//w w w. ja va 2 s.c o m * @param url is the url to post to. * @return the return string from the server. * @throws java.io.IOException */ public static String postData(String data, URL url) throws IOException { String result = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { HttpHelpers.addCommonHeaders(conn); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); String line; BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn); while ((line = reader.readLine()) != null) { if (result == null) result = line; else result += line; } reader.close(); } catch (IOException ex) { Log.e(TAG, "Failed to read stream data", ex); String error = null; // TODO Am not yet sure if the section below should make it in the production release. // I mainly use it to get details of a failed http request. I get a FileNotFoundException // when actually the url is correct but an exception was thrown at the server and i use this // to get the server call stack for debugging purposes. try { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); while ((line = reader.readLine()) != null) { if (error == null) error = line; else error += line; } reader.close(); } catch (Exception e) { Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex); } } return result; }
From source file:com.bellman.bible.service.common.CommonUtils.java
/** return true if URL is accessible * // w ww.j a va 2s . c o m * Since Android 3 must do on different or NetworkOnMainThreadException is thrown */ public static boolean isHttpUrlAvailable(final String urlString) { boolean isAvailable = false; final int TIMEOUT_MILLIS = 3000; try { class CheckUrlThread extends Thread { public boolean checkUrlSuccess = false; public void run() { HttpURLConnection connection = null; try { // might as well test for the url we need to access URL url = new URL(urlString); Log.d(TAG, "Opening test connection"); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIMEOUT_MILLIS); connection.setReadTimeout(TIMEOUT_MILLIS); connection.setRequestMethod("HEAD"); Log.d(TAG, "Connecting to test internet connection"); connection.connect(); checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK); Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess); } catch (IOException e) { Log.i(TAG, "No internet connection"); checkUrlSuccess = false; } finally { if (connection != null) { connection.disconnect(); } } } } CheckUrlThread checkThread = new CheckUrlThread(); checkThread.start(); checkThread.join(TIMEOUT_MILLIS); isAvailable = checkThread.checkUrlSuccess; } catch (InterruptedException e) { Log.e(TAG, "Interrupted waiting for url check to complete", e); } return isAvailable; }
From source file:info.icefilms.icestream.browse.Location.java
private static Bitmap DownloadImage(URL url, Callback callback) { try {/* w w w .j a va 2s . c o m*/ // Open the connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0"); urlConnection.setConnectTimeout(callback.GetConnectionTimeout()); urlConnection.setReadTimeout(callback.GetConnectionTimeout()); urlConnection.connect(); // Get the input stream InputStream inputStream = urlConnection.getInputStream(); // For some reason we can actually get a null InputStream instead of an exception if (inputStream == null) { Log.e("Ice Stream", "Image download failed. Unable to create Input Stream."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_download_error); } urlConnection.disconnect(); return null; } // Download the image and create the bitmap Bitmap bitmap = BitmapFactory.decodeStream(inputStream); // Close the connection inputStream.close(); urlConnection.disconnect(); // Check for errors if (bitmap == null) { Log.e("Ice Stream", "Image data decoding failed."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_decode_error); } return null; } return bitmap; } catch (SocketTimeoutException exception) { Log.e("Ice Stream", "Image download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_timeout_error); } return null; } catch (IOException exception) { Log.e("Ice Stream", "Image download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_download_error); } return null; } }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Object getCoinValueBTC_cryptopia() { //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;/*from ww w . j a v a 2 s. c o m*/ String currency = "BTC"; String url = "https://www.cryptopia.co.nz/api/GetMarket/2623"; try { // final String currencyCode = currencies[i]; final URL URL_bter = new URL(url); final HttpURLConnection connection = (HttpURLConnection) URL_bter.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); /*{ "Success":true, "Message":null, "Data":{ "TradePairId":100, "Label":"LTC/BTC", "AskPrice":0.00006000, "BidPrice":0.02000000, "Low":0.00006000, "High":0.00006000, "Volume":1000.05639978, "LastPrice":0.00006000, "LastVolume":499.99640000, "BuyVolume":67003436.37658233, "SellVolume":67003436.37658233, "Change":-400.00000000 } }*/ String result = head.getString("Success"); if (result.equals("true")) { JSONObject dataObject = head.getJSONObject("Data"); Double averageTrade = Double.valueOf(0.0); if (dataObject.get("Label").equals("GLD/BTC")) averageTrade = dataObject.getDouble("LastPrice"); if (currency.equalsIgnoreCase("BTC")) btcRate = averageTrade; } return btcRate; } finally { if (reader != null) reader.close(); } } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:cn.kk.exia.MangaDownloader.java
public final static HttpURLConnection getUrlConnection(final String url, final boolean post, final String output) throws IOException { int retries = 0; HttpURLConnection conn; while (true) { try {//from www . ja v a 2 s .co m final URL urlObj = new URL(url); conn = (HttpURLConnection) urlObj.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(30000); if (post) { conn.setRequestMethod("POST"); } final String referer; final int pathIdx; if ((pathIdx = url.lastIndexOf('/')) > "https://".length()) { referer = url.substring(0, pathIdx); } else { referer = url; } conn.setRequestProperty("Referer", referer); final Set<String> keys = MangaDownloader.DEFAULT_CONN_HEADERS.keySet(); for (final String k : keys) { final String value = MangaDownloader.DEFAULT_CONN_HEADERS.get(k); if (value != null) { conn.setRequestProperty(k, value); } } // conn.setUseCaches(false); if (output != null) { conn.setDoOutput(true); final BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(output.getBytes(MangaDownloader.CHARSET_UTF8)); out.close(); } if (MangaDownloader.appendCookies(MangaDownloader.cookie, conn)) { MangaDownloader.putConnectionHeader("Cookie", MangaDownloader.cookie.toString()); } break; } catch (final Throwable e) { // System.err.println(e.toString()); if (retries++ > 10) { throw new IOException(e); } else { try { Thread.sleep((60 * retries * MangaDownloader.sleepBase) + ((int) Math.random() * MangaDownloader.sleepBase * 60 * retries)); } catch (final InterruptedException e1) { e1.printStackTrace(); } } } } return conn; }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBitcoinCharts() { try {// w w w . j a v a2 s . com // double btcRate = getGoldCoinValueBTC(); //NullPointerException??? Double btcRate = 0.0; Object result = getGoldCoinValueBTC_ccex(); if (result == null) { result = getCoinValueBTC_cryptopia(); if (result == null) return null; else btcRate = (Double) result; } 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)); final StringBuilder content = new StringBuilder(); IOUtils.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put("BTC", new ExchangeRate("BTC", 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) rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } } return rates; } finally { if (reader != null) reader.close(); } } catch (final IOException x) { // log.debug("problem reading exchange rates", x); x.printStackTrace(); } catch (final JSONException x) { //log.debug("problem reading exchange rates", x); x.printStackTrace(); } return null; }