List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Object getCoinValueBTC_BTER() { 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 ww.java2 s.c o m*/ String currency = CoinDefinition.cryptsyMarketCurrency; String url = "https://bittrex.com/api/v1.1/public/getticker?market=BTC-CANN"; HttpURLConnection connection = null; try { // final String currencyCode = currencies[i]; final URL URL_bter = new URL(url); 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)); Io.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); String result = head.getString("result"); if (result.equals("true")) { Double averageTrade = head.getDouble("Bid"); if (currency.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 (connection != null) connection.disconnect(); } return null; }
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 {//from w w w.ja v a 2 s . c om 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:com.iStudy.Study.Renren.Util.java
private static HttpURLConnection sendFormdata(String reqUrl, Bundle parameters, String fileParamName, String filename, String contentType, byte[] data) { HttpURLConnection urlConn = null; try {//ww w .j a v a 2s.c o m URL url = new URL(reqUrl); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(5000);// ??jdk urlConn.setReadTimeout(5000);// ??jdk 1.5??,? urlConn.setDoOutput(true); urlConn.setRequestProperty("connection", "keep-alive"); String boundary = "-----------------------------114975832116442893661388290519"; // urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; StringBuffer params = new StringBuffer(); if (parameters != null) { for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) { String name = iter.next(); String value = parameters.getString(name); params.append(boundary + "\r\n"); params.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"); // params.append(URLEncoder.encode(value, "UTF-8")); params.append(value); params.append("\r\n"); } } StringBuilder sb = new StringBuilder(); sb.append(boundary); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + filename + "\"\r\n"); sb.append("Content-Type: " + contentType + "\r\n\r\n"); byte[] fileDiv = sb.toString().getBytes(); byte[] endData = ("\r\n" + boundary + "--\r\n").getBytes(); byte[] ps = params.toString().getBytes(); OutputStream os = urlConn.getOutputStream(); os.write(ps); os.write(fileDiv); os.write(data); os.write(endData); os.flush(); os.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return urlConn; }
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 . j a 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: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 w w w . j a v a 2 s . c om 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:msearch.filmeSuchen.sender.MediathekSrf.java
public static boolean ping(String url) throws SRFException { url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates. try {/*from w w w . j ava2s .co m*/ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity connection.setReadTimeout(0); int responseCode = connection.getResponseCode(); connection.disconnect(); if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new SRFException("TEST"); } //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url); return false; } return (200 <= responseCode && responseCode <= 399); } catch (IOException exception) { return false; } }
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 ww.j a va2s .co 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.stockita.popularmovie.utility.Utilities.java
/** * This will make a GET request to a RESTful web. * * @return String of JSON format/*ww w . jav a 2s .com*/ */ public static String getMovieData(String uri, Context context) { BufferedReader reader = null; HttpURLConnection con = null; try { URL url = new URL(uri); con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(10000 /* milliseconds */); con.setConnectTimeout(15000 /* milliseconds */); con.setRequestMethod(REQUEST_METHOD_GET); con.connect(); int response = con.getResponseCode(); if (response < 200 || response > 299) { Log.e(LOG_TAG, "connection failed: " + response); sNetworkResponse = false; return null; } InputStream inputStream = con.getInputStream(); // Return null if no date if (inputStream == null) { Log.e(LOG_TAG, "inputStream returned null"); return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } // Return null if no data if (builder.length() == 0) { Log.e(LOG_TAG, "builder return null"); return null; } return builder.toString(); } catch (IOException e) { Log.e(LOG_TAG, e.toString()); sNetworkResponse = false; return null; } finally { try { if (reader != null) reader.close(); if (con != null) con.disconnect(); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_TAG, e.toString()); } } }
From source file:com.bellman.bible.service.common.CommonUtils.java
/** return true if URL is accessible * /*from w ww .j a v a2 s.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: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;/*www . j a v a2s.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; }