List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:org.digitalcampus.oppia.task.DownloadMediaTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];/*from w w w .jav a 2s. c om*/ for (Object o : payload.getData()) { Media m = (Media) o; File file = new File(MobileLearning.MEDIA_PATH, m.getFilename()); try { URL u = new URL(m.getDownloadUrl()); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); DownloadProgress dp = new DownloadProgress(); dp.setMessage(m.getFilename()); dp.setProgress(0); publishProgress(dp); FileOutputStream f = new FileOutputStream(file); InputStream in = c.getInputStream(); MessageDigest md = MessageDigest.getInstance("MD5"); in = new DigestInputStream(in, md); byte[] buffer = new byte[8192]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); // check the file digest matches, otherwise delete the file // (it's either been a corrupted download or it's the wrong file) byte[] digest = md.digest(); String resultMD5 = ""; for (int i = 0; i < digest.length; i++) { resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); } Log.d(TAG, "supplied digest: " + m.getDigest()); Log.d(TAG, "calculated digest: " + resultMD5); if (!resultMD5.contains(m.getDigest())) { this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } else { payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename())); } } catch (ClientProtocolException e1) { e1.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (IOException e1) { e1.printStackTrace(); this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (NoSuchAlgorithmException e) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(e); } else { e.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } } return payload; }
From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address address) { backgroundHandler.post(new Runnable() { @Override//from ww w . j a v a 2 s. co m public void run() { // Use either dogechain or chain.so List<String> urls = new ArrayList<String>(2); urls.add(Constants.DOGECHAIN_API_URL); urls.add(Constants.CHAINSO_API_URL); Collections.shuffle(urls, new Random(System.nanoTime())); final StringBuilder url = new StringBuilder(urls.get(0)); url.append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int success = json.getInt("success"); if (success != 1) throw new IOException("api status " + success + " when fetching unspent outputs"); final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash")); final int uxtoIndex = jsonOutput.getInt("tx_output_n"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
From source file:libthrift091.transport.THttpClient.java
public void flush() throws TTransportException { if (null != this.client) { flushUsingHttpClient();/*from w w w. j a v a 2 s . c o m*/ return; } // Extract request and reset buffer byte[] data = requestBuffer_.toByteArray(); requestBuffer_.reset(); try { // Create connection object HttpURLConnection connection = (HttpURLConnection) url_.openConnection(); // Timeouts, only if explicitly set if (connectTimeout_ > 0) { connection.setConnectTimeout(connectTimeout_); } if (readTimeout_ > 0) { connection.setReadTimeout(readTimeout_); } // Make the request connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-thrift"); connection.setRequestProperty("Accept", "application/x-thrift"); connection.setRequestProperty("User-Agent", "Java/THttpClient"); if (customHeaders_ != null) { for (Map.Entry<String, String> header : customHeaders_.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } } connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(data); int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new TTransportException("HTTP Response code: " + responseCode); } // Read the responses inputStream_ = connection.getInputStream(); } catch (IOException iox) { throw new TTransportException(iox); } }
From source file:com.zhonghui.tool.controller.HttpClient.java
/** * get/*from w ww. java 2 s . c o m*/ * * @return * @throws ProtocolException */ private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException { HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } httpURLConnection.setConnectTimeout(this.connectionTimeout);// httpURLConnection.setReadTimeout(this.readTimeOut);// ? httpURLConnection.setUseCaches(false);// ? httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=" + encoding); httpURLConnection.setRequestMethod("GET"); return httpURLConnection; }
From source file:com.zhonghui.tool.controller.HttpClient.java
/** * Post//from w w w. ja v a2 s. com * * @return * @throws ProtocolException */ private HttpURLConnection createConnection(String encoding) throws ProtocolException { HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } httpURLConnection.setConnectTimeout(this.connectionTimeout);// httpURLConnection.setReadTimeout(this.readTimeOut);// ? httpURLConnection.setDoInput(true); // ? post? httpURLConnection.setDoOutput(true); // ? post? httpURLConnection.setUseCaches(false);// ? httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=" + encoding); httpURLConnection.setRequestMethod("POST"); return httpURLConnection; }
From source file:edu.usf.cutr.opentripplanner.android.tasks.MetadataRequest.java
protected GraphMetadata doInBackground(String... reqs) { String prefix = PreferenceManager.getDefaultSharedPreferences(context) .getString(OTPApp.PREFERENCE_KEY_FOLDER_STRUCTURE_PREFIX, OTPApp.FOLDER_STRUCTURE_PREFIX_NEW); String u = reqs[0] + prefix + OTPApp.METADATA_LOCATION; Log.d(OTPApp.TAG, "URL: " + u); HttpURLConnection urlConnection = null; GraphMetadata metadata = null;// ww w. j a v a 2s . c o m try { URL url = new URL(u); if (mapper == null) { mapper = new ObjectMapper(); } mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); metadata = mapper.readValue(urlConnection.getInputStream(), GraphMetadata.class); } catch (IOException e) { Log.e(OTPApp.TAG, "Error fetching JSON or XML: " + e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return metadata; }
From source file:ja.ohac.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override// ww w . j a v a 2 s. c o m public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = BaseEncoding.base16().lowerCase() .decode(jsonOutput.getString("script_pub_key")); final BigInteger uxtoValue = new BigInteger(jsonOutput.getString("value")); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.valueOf(uxtoValue.longValue()), uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
From source file:edu.usf.cutr.opentripplanner.android.tasks.BikeRentalLoad.java
protected BikeRentalStationList doInBackground(String... reqs) { String prefix = PreferenceManager.getDefaultSharedPreferences(context) .getString(OTPApp.PREFERENCE_KEY_FOLDER_STRUCTURE_PREFIX, OTPApp.FOLDER_STRUCTURE_PREFIX_NEW); String u = reqs[0] + prefix + OTPApp.BIKE_RENTAL_LOCATION; Log.d(OTPApp.TAG, "URL: " + u); HttpURLConnection urlConnection = null; BikeRentalStationList bikeRentalStationList = null; try {/*from w ww. ja va 2s . c o m*/ URL url = new URL(u); if (mapper == null) { mapper = new ObjectMapper(); } mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); bikeRentalStationList = mapper.readValue(urlConnection.getInputStream(), BikeRentalStationList.class); } catch (IOException e) { Log.e(OTPApp.TAG, "Error fetching JSON or XML: " + e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return bikeRentalStationList; }
From source file:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java
private void checkStatus(ServiceType serviceStatus) { HttpURLConnection urlConnection = null; InputStream contentStream = null; InputStream countStream = null; try {//from w ww .ja v a2 s . co m final URL versionUrl = new URL(serviceStatus.getRestUrl() + "version"); final URL countURL = new URL(serviceStatus.getRestUrl() + "query/*?format=count"); urlConnection = (HttpURLConnection) versionUrl.openConnection(); urlConnection.setConnectTimeout(threadTimeOut * 1000); urlConnection.setReadTimeout(threadTimeOut * 1000); urlConnection.connect(); int code = urlConnection.getResponseCode(); if (HttpURLConnection.HTTP_OK == code) { serviceStatus.setActive(true); final String version; final String strCount; //TODO Add a double check to know if the service is active // or not add a catch block for the exceptions contentStream = (InputStream) urlConnection.getContent(); version = IOUtils.toString(contentStream); serviceStatus.setVersion(version); countStream = (InputStream) countURL.getContent(); strCount = IOUtils.toString(countStream); serviceStatus.setCount(Long.valueOf(strCount)); } else { serviceStatus.setActive(false); } } catch (Throwable e) { serviceStatus.setActive(false); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { log.error("Cannot close psicquic content stream", e); } } if (countStream != null) { try { countStream.close(); } catch (IOException e) { log.error("Cannot close psicquic count stream", e); } } if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override//from w w w. j a v a2 s.com public void run() { final StringBuilder url = new StringBuilder(Constants.BITEASY_API_URL); url.append("unspent-outputs"); url.append("?per_page=MAX"); for (final Address address : addresses) url.append("&address[]=").append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IllegalStateException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); if (jsonOutput.getInt("is_spent") != 0) throw new IllegalStateException("UXTO not spent"); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script_pub_key")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }