List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address address) { backgroundHandler.post(new Runnable() { @Override/*from w w 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:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private HttpURLConnection openConnection(String uri, String method) { for (String host : hosts) { try {//from w w w .j a va2 s . c o m URL templateUrl = new URL("http://" + host + uri); HttpURLConnection connection = (HttpURLConnection) templateUrl.openConnection(); connection.setRequestMethod(method); connection.setConnectTimeout(timeout); connection.setUseCaches(false); if ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) { connection.setDoOutput(true); } connection.connect(); return connection; } catch (IOException e) { LOGGER.error("Error connecting to {}: {}", host, e); } } throw new ElasticsearchConnectionException( "Error connecting to elasticsearch host(s): " + Arrays.toString(hosts)); }
From source file:com.box.androidlib.BoxSynchronous.java
/** * Executes an Http request and triggers response parsing by the specified parser. * // ww w. j av a2 s . c om * @param parser * A BoxResponseParser configured to consume the response and capture data that is of interest * @param uri * The Uri of the request * @throws IOException * Can be thrown if there is no connection, or if some other connection problem exists. */ protected static void saxRequest(final DefaultResponseParser parser, final Uri uri) throws IOException { Uri theUri = uri; List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters(); if (customQueryParams != null && customQueryParams.size() > 0) { Uri.Builder builder = theUri.buildUpon(); for (BasicNameValuePair param : customQueryParams) { builder.appendQueryParameter(param.getName(), param.getValue()); } theUri = builder.build(); } try { final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); xmlReader.setContentHandler(parser); HttpURLConnection conn = (HttpURLConnection) (new URL(theUri.toString())).openConnection(); conn.setRequestProperty("User-Agent", BoxConfig.getInstance().getUserAgent()); conn.setRequestProperty("Accept-Language", BoxConfig.getInstance().getAcceptLanguage()); conn.setConnectTimeout(BoxConfig.getInstance().getConnectionTimeOut()); if (mLoggingEnabled) { DevUtils.logcat("URL: " + theUri.toString()); // Iterator<String> keys = conn.getRequestProperties().keySet().iterator(); // while (keys.hasNext()) { // String key = keys.next(); // DevUtils.logcat("Request Header: " + key + " => " + conn.getRequestProperties().get(key)); // } } int responseCode = -1; try { conn.connect(); responseCode = conn.getResponseCode(); if (mLoggingEnabled) DevUtils.logcat("Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); xmlReader.parse(new InputSource(inputStream)); inputStream.close(); } else if (responseCode == -1) { parser.setStatus(ResponseListener.STATUS_UNKNOWN_HTTP_RESPONSE_CODE); } } catch (IOException e) { try { responseCode = conn.getResponseCode(); } catch (NullPointerException ee) { // Honeycomb devices seem to throw a null pointer exception sometimes which traces to HttpURLConnectionImpl. } // Server returned a 503 Service Unavailable. Usually means a temporary unavailability. if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) { parser.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE); } else { throw e; } } finally { conn.disconnect(); } } catch (final ParserConfigurationException e) { e.printStackTrace(); } catch (final SAXException e) { e.printStackTrace(); } catch (final FactoryConfigurationError e) { e.printStackTrace(); } }
From source file:cm.aptoide.pt.util.NetworkUtils.java
public int checkServerConnection(final String string, final String username, final String password) { try {// w w w .j av a 2 s.c om HttpURLConnection client = (HttpURLConnection) new URL(string + "info.xml").openConnection(); if (username != null && password != null) { String basicAuth = "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP)); client.setRequestProperty("Authorization", basicAuth); } client.setConnectTimeout(TIME_OUT); client.setReadTimeout(TIME_OUT); if (ApplicationAptoide.DEBUG_MODE) Log.i("Aptoide-NetworkUtils-checkServerConnection", "Checking on: " + client.getURL().toString()); if (client.getContentType().equals("application/xml")) { return 0; } else { return client.getResponseCode(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return -1; }
From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java
/** * ??(?????// w w w .j a v a2 s. c o m * ??????) */ private void initDownloadInfo() { int totalSize = 0; if (isFirst(mUrl)) { HttpURLConnection connection = null; try { URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT_MILLISECOND); connection.setRequestMethod("GET"); System.getProperties().setProperty("http.nonProxyHosts", url.getHost()); // cookie? setCookieProperty(connection, mUrl); if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { totalSize = connection.getContentLength(); if (-1 != totalSize) { mDownloadInfo = new FileDownloadInfo(totalSize, 0, mUrl); // ?mDownloadInfo?? mFileTransferRecorder.saveDownloadInfo(mDownloadInfo); } else { XLog.e(CLASS_NAME, "cannot get totalSize"); } // temp File file = new File(mLocalFilePath + TEMP_FILE_SUFFIX); if (file.exists()) { file.delete(); } } } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); } finally { if (null != connection) { connection.disconnect(); } } } else { // ?url? mDownloadInfo = mFileTransferRecorder.getDownloadInfo(mUrl); totalSize = mDownloadInfo.getTotalSize(); mDownloadInfo.setCompleteSize(getCompleteSize(mLocalFilePath + TEMP_FILE_SUFFIX)); } mBufferSize = getSingleTransferLength(totalSize); }
From source file:foam.starwisp.NetworkManager.java
private void Post(String u, String type, String data, String CallbackName) { try {// w w w . j a v a 2s .c o m Log.i("starwisp", "posting: " + u); URL url = new URL(u); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); con.setReadTimeout(100000 /* milliseconds */); con.setConnectTimeout(150000 /* milliseconds */); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("data", data)); OutputStream os = con.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); // Starts the query con.connect(); m_RequestHandler.sendMessage( Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName))); } catch (Exception e) { Log.i("starwisp", e.toString()); e.printStackTrace(); } }
From source file:net.phalapi.sdk.PhalApiClient.java
protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception { String result = null;/*from w ww . j a va 2s . c o m*/ URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); // ? connection.setUseCaches(false); connection.setConnectTimeout(timeoutMs); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //POST? String postContent = ""; Iterator<Entry<String, String>> iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); postContent += "&" + entry.getKey() + "=" + entry.getValue(); } out.writeBytes(postContent); out.flush(); out.close(); Log.d("[PhalApiClient requestUrl]", requestUrl + postContent); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.d("[PhalApiClient apiResult]", result); if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
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;// w w w .j av a 2 s .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// w w w . j a v a2 s. co 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(); } } }); }