List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.rimbit.android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;/*from ww w .j a v a 2s . c o m*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, RIMBIT_EXPLORER_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + RIMBIT_EXPLORER_URL, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.magnet.plugin.helpers.URLHelper.java
public static InputStream loadUrl(final String url) throws Exception { final InputStream[] inputStreams = new InputStream[] { null }; final Exception[] exception = new Exception[] { null }; Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { try { HttpURLConnection connection; if (ApplicationManager.getApplication() != null) { connection = HttpConfigurable.getInstance().openHttpConnection(url); } else { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT); connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT); }/* w w w . j a v a2s . c om*/ connection.connect(); inputStreams[0] = connection.getInputStream(); } catch (IOException e) { exception[0] = e; } } }); try { downloadThreadFuture.get(5, TimeUnit.SECONDS); } catch (TimeoutException ignored) { } if (!downloadThreadFuture.isDone()) { downloadThreadFuture.cancel(true); throw new ConnectionException(IdeBundle.message("updates.timeout.error")); } if (exception[0] != null) throw exception[0]; return inputStreams[0]; }
From source file:net.nym.library.http.UploadImagesRequest.java
/** * ???//www . j a v a2 s. c o m * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws java.io.IOException */ public static String postFile(String url, Map<String, Object> params, Map<String, File> files) throws IOException { String result = ""; String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; StringBuilder sb = new StringBuilder("?"); for (Map.Entry<String, Object> entry : params.entrySet()) { // sb.append(PREFIX); // sb.append(BOUNDARY); // sb.append(LINEND); // sb.append("Content-Disposition: form-data; name=\"" // + entry.getKey() + "\"" + LINEND); // sb.append("Content-Type: text/plain; charset=" + CHARSET // + LINEND); // sb.append("Content-Transfer-Encoding: 8bit" + LINEND); // sb.append(LINEND); // sb.append(entry.getValue()); // sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString())) .append("&"); } sb.deleteCharAt(sb.length() - 1); URL uri = new URL(url + sb.toString()); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setDoInput(true);// ? conn.setDoOutput(true);// ? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // ? // StringBuilder sb = new StringBuilder(); // for (Map.Entry<String, Object> entry : params.entrySet()) { //// sb.append(PREFIX); //// sb.append(BOUNDARY); //// sb.append(LINEND); //// sb.append("Content-Disposition: form-data; name=\"" //// + entry.getKey() + "\"" + LINEND); //// sb.append("Content-Type: text/plain; charset=" + CHARSET //// + LINEND); //// sb.append("Content-Transfer-Encoding: 8bit" + LINEND); //// sb.append(LINEND); //// sb.append(entry.getValue()); //// sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); // } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); // outStream.write(sb.toString().getBytes()); // ? if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sbFile = new StringBuilder(); sbFile.append(PREFIX); sbFile.append(BOUNDARY); sbFile.append(LINEND); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sbFile.append(LINEND); Log.i(sbFile.toString()); outStream.write(sbFile.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // ? byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); } outStream.flush(); // ?? int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sbResult = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sbResult.append((char) ch); } } result = sbResult.toString(); outStream.close(); conn.disconnect(); return result; }
From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java
public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring) throws OpenUriException { if (uri == null) { throw new IllegalArgumentException("Uri cannot be empty"); }// w w w . java 2 s . c om String scheme = uri.getScheme(); if (scheme == null) { throw new OpenUriException(false, new IOException("Uri had no scheme")); } InputStream in = null; if ("content".equals(scheme)) { try { in = context.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { throw new OpenUriException(false, e); } catch (SecurityException e) { throw new OpenUriException(false, e); } } else if ("file".equals(scheme)) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) { AssetManager assetManager = context.getAssets(); StringBuilder assetPath = new StringBuilder(); for (int i = 1; i < segments.size(); i++) { if (i > 1) { assetPath.append("/"); } assetPath.append(segments.get(i)); } try { in = assetManager.open(assetPath.toString()); } catch (IOException e) { throw new OpenUriException(false, e); } } else { try { in = new FileInputStream(new File(uri.getPath())); } catch (FileNotFoundException e) { throw new OpenUriException(false, e); } } } else if ("http".equals(scheme) || "https".equals(scheme)) { OkHttpClient client = new OkHttpClient(); HttpURLConnection conn = null; int responseCode = 0; String responseMessage = null; try { conn = client.open(new URL(uri.toString())); conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); conn.setReadTimeout(DEFAULT_READ_TIMEOUT); responseCode = conn.getResponseCode(); responseMessage = conn.getResponseMessage(); if (!(responseCode >= 200 && responseCode < 300)) { throw new IOException("HTTP error response."); } if (reqContentTypeSubstring != null) { String contentType = conn.getContentType(); if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) { throw new IOException("HTTP content type '" + contentType + "' didn't match '" + reqContentTypeSubstring + "'."); } } in = conn.getInputStream(); } catch (MalformedURLException e) { throw new OpenUriException(false, e); } catch (IOException e) { if (conn != null && responseCode > 0) { throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e); } else { throw new OpenUriException(false, e); } } } return in; }
From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;//from www.ja va2 s . c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, BTCE_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + BTCE_URL, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;/*from w w w. ja v a 2s. co m*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:org.immopoly.android.helper.WebHelper.java
public static JSONObject getHttpsData(URL url, boolean signed, Context context) throws ImmopolyException { JSONObject obj = null;/*ww w.j a v a2 s . c o m*/ if (Settings.isOnline(context)) { HttpURLConnection request; try { request = (HttpURLConnection) url.openConnection(); request.addRequestProperty("User-Agent", "immopoly android client " + ImmopolyActivity.getStaticVersionInfo()); if (signed) OAuthData.getInstance(context).consumer.sign(request); request.setConnectTimeout(SOCKET_TIMEOUT); request.connect(); InputStream in = new BufferedInputStream(request.getInputStream()); String s = readInputStream(in); JSONTokener tokener = new JSONTokener(s); return new JSONObject(tokener); } catch (JSONException e) { throw new ImmopolyException("Kommunikationsproblem (beim lesen der Antwort)", e); } catch (MalformedURLException e) { throw new ImmopolyException("Kommunikationsproblem (fehlerhafte URL)", e); } catch (OAuthMessageSignerException e) { throw new ImmopolyException("Kommunikationsproblem (Signierung)", e); } catch (OAuthExpectationFailedException e) { throw new ImmopolyException("Kommunikationsproblem (Sicherherit)", e); } catch (OAuthCommunicationException e) { throw new ImmopolyException("Kommunikationsproblem (Sicherherit)", e); } catch (IOException e) { throw new ImmopolyException("Kommunikationsproblem", e); } } else throw new ImmopolyException("Kommunikationsproblem (Offline)"); }
From source file:com.mopaas_mobile.http.BaseHttpRequester.java
public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException { String result = null;/* w w w . ja v a2s .c o m*/ URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // connection.setRequestProperty("token",token); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); String content = ""; if (params != null && params.size() > 0) { for (int i = 0; i < params.size(); i++) { content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8"); } out.writeBytes(content.substring(1)); } out.flush(); out.close(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer b = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { b.append((char) ch); } result = b.toString().trim(); connection.disconnect(); return result; }
From source file:ja.ohac.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;// ww w. ja va 2 s . c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Charsets.UTF_8); final StringBuilder content = new StringBuilder(); final long length = Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); 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); for (final String field : fields) { final String rateStr = o.optString(field, null); if (rateStr != null) { try { final BigInteger rate = GenericUtils.parseCoin(rateStr, 0); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source)); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.edgenius.wiki.Shell.java
/** * @param url/*from w w w .ja v a2s. c om*/ * @return */ private static boolean notifyShell(String url) { if (StringUtils.isEmpty(Shell.key)) { //I suppose all notify methods will execute in backend thread, i.e., MQ consumer. This won't use new thread to avoid thread block. if (!requestInstanceShellKey()) { log.error("Unable to locate Shell key value from shell hosting {}", url); return false; } } try { log.info("Notify shell {}", url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty(HEAD_SHELL_KEY, Shell.key); conn.setConnectTimeout(timeout); return (conn.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (IOException e) { log.error("Unable to connect shell for notification", e); } catch (Throwable e) { log.error("Notify shell failure", e); } return false; }