List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:info.icefilms.icestream.browse.Location.java
private static Bitmap DownloadImage(URL url, Callback callback) { try {//ww w . j a v a 2 s .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 w w w.j a v a 2s . com 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:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBitcoinCharts() { try {/*from w ww.j a v a 2s . c o m*/ // 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; }
From source file:fr.mixit.android.utils.NetworkUtils.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) static ResponseHttp getInputStreamFromHttpUrlConnection(String url, boolean isPost, String args) { final ResponseHttp myResponse = new ResponseHttp(); HttpURLConnection urlConnection = null; if (cookieManager == null) { cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); }//from ww w . j a v a 2 s . c o m try { String urlWithParams = url; if (!isPost && args != null) { urlWithParams = getGetURL(url, args); } final URL urlObject = new URL(urlWithParams); urlConnection = (HttpURLConnection) urlObject.openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); urlConnection.setReadTimeout(SOCKET_TIMEOUT); // if (cookieSession != null) { // cookieManager.getCookieStore().removeAll(); // cookieManager.getCookieStore().addCookie(cookieSession); // } if (isPost) { urlConnection.setDoOutput(true); } // urlConnection.connect(); if (isPost && args != null) { final byte[] params = args.getBytes(HTTP.UTF_8); urlConnection.setFixedLengthStreamingMode(params.length);// or urlConnection.setChunkedStreamingMode(0); final OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(params); } myResponse.status = urlConnection.getResponseCode(); if (DEBUG_MODE) { Log.d(TAG, "Status code : " + myResponse.status); } myResponse.jsonText = getJson(urlConnection.getInputStream()); } catch (final MalformedURLException e) { if (DEBUG_MODE) { Log.e(TAG, "The URL is malformatted", e); } } catch (final IllegalAccessError e) { if (DEBUG_MODE) { Log.e(TAG, "setDoOutput after openning a connection or already done"); } } catch (final UnsupportedEncodingException e) { if (DEBUG_MODE) { Log.e(TAG, "UTF8 unsupported for args", e); } } catch (final IllegalStateException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } catch (final IllegalArgumentException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } catch (final IOException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return myResponse; }
From source file:io.sloeber.core.managers.Manager.java
/** * copy a url locally taking into account redirections * * @param url/*from ww w . j av a2s. c o m*/ * @param localFile */ @SuppressWarnings("nls") private static void myCopy(URL url, File localFile) { try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(), REPLACE_EXISTING); } else { Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING); } } catch (Exception e) { Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e)); } }
From source file:com.dopecoin.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from w ww . ja v a 2 s . c o m*/ URL providerUrl; switch (provider) { case 0: providerUrl = DOPEPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = DOPEPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("DOPE") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:in.leafco.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from w ww . j a v a 2 s .c o m*/ URL providerUrl; switch (provider) { case 0: providerUrl = LEAFPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = LEAFPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("LEAF") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:de.jdellay.wallet.ExchangeRatesProvider.java
private static float requestCcnBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/*from w w w . j av a 2s .c o m*/ URL providerUrl; switch (provider) { case 0: providerUrl = CCNPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = CCNPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("CCN") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:com.screenslicer.common.CommonUtil.java
public static void postQuickly(String uri, String recipient, String postData) { HttpURLConnection conn = null; try {//from ww w. j a v a 2 s . c om postData = Crypto.encode(postData, recipient); conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setRequestProperty("Content-Type", "application/json"); byte[] bytes = postData.getBytes("utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient); } catch (Exception e) { Log.exception(e); } }
From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java
private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri, String postBody, StoredFile storedFile) { Log.d("Performing multipart request to %s", uri); ApptentiveHttpResponse ret = new ApptentiveHttpResponse(); if (storedFile == null) { Log.e("StoredFile is null. Unable to send."); return ret; }//from w w w . j ava 2 s. com int bytesRead; int bufferSize = 4096; byte[] buffer; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = UUID.randomUUID().toString(); HttpURLConnection connection; DataOutputStream os = null; InputStream is = null; try { is = context.openFileInput(storedFile.getLocalFilePath()); // Set up the request. URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("Authorization", "OAuth " + oauthToken); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-API-Version", API_VERSION); connection.setRequestProperty("User-Agent", getUserAgentString()); StringBuilder requestText = new StringBuilder(); // Write form data requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd); requestText.append("Content-Type: text/plain").append(lineEnd); requestText.append(lineEnd); requestText.append(postBody); requestText.append(lineEnd); // Write file attributes. requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", storedFile.getFileName())).append(lineEnd); requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd); requestText.append(lineEnd); Log.d("Post body: " + requestText); // Open an output stream. os = new DataOutputStream(connection.getOutputStream()); // Write the text so far. os.writeBytes(requestText.toString()); try { // Write the actual file. buffer = new byte[bufferSize]; while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { Log.d("Error writing file bytes to HTTP connection.", e); ret.setBadPayload(true); throw e; } os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); os.close(); ret.setCode(connection.getResponseCode()); ret.setReason(connection.getResponseMessage()); // TODO: These streams may not be ready to read now. Put this in a new thread. // Read the normal response. InputStream nis = null; ByteArrayOutputStream nbaos = null; try { Log.d("Sending file: " + storedFile.getLocalFilePath()); nis = connection.getInputStream(); nbaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) { nbaos.write(eBuf, 0, eRead); } ret.setContent(nbaos.toString()); } catch (IOException e) { Log.w("Can't read return stream.", e); } finally { Util.ensureClosed(nis); Util.ensureClosed(nbaos); } // Read the error response. InputStream eis = null; ByteArrayOutputStream ebaos = null; try { eis = connection.getErrorStream(); ebaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) { ebaos.write(eBuf, 0, eRead); } if (ebaos.size() > 0) { ret.setContent(ebaos.toString()); } } catch (IOException e) { Log.w("Can't read error stream.", e); } finally { Util.ensureClosed(eis); Util.ensureClosed(ebaos); } Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + ""); Log.v(ret.getContent()); } catch (FileNotFoundException e) { Log.e("Error getting file to upload.", e); } catch (MalformedURLException e) { Log.e("Error constructing url for file upload.", e); } catch (SocketTimeoutException e) { Log.w("Timeout communicating with server."); } catch (IOException e) { Log.e("Error executing file upload.", e); } finally { Util.ensureClosed(is); Util.ensureClosed(os); } return ret; }