List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java
@SuppressWarnings("unchecked") public static void authServer16(String hash) throws IOException { URL url;//from w w w . jav a 2 s. c o m String username; String accessToken; try { if (loginDetails == null) { throw new IOException("Not logged in"); } try { username = URLEncoder.encode(getUsername(), "UTF-8"); accessToken = URLEncoder.encode(getAccessToken(), "UTF-8"); hash = URLEncoder.encode(hash, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IOException("Username/password encoding error", e); } String urlString; urlString = sessionServer16 + "user=" + username + "&sessionId=" + accessToken + "&serverId=" + hash; url = new URL(urlString); } catch (MalformedURLException e) { throw new IOException("Auth server URL error", e); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setInstanceFollowRedirects(false); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.connect(); if (con.getResponseCode() != 200) { throw new IOException("Auth server rejected username and password"); } BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); try { String reply = reader.readLine(); if (!"OK".equals(reply)) { throw new IOException("Auth server replied (" + reply + ")"); } } finally { reader.close(); con.disconnect(); } }
From source file:org.tinymediamanager.core.License.java
public static boolean encrypt(Properties props) { try {/* ww w .ja v a2 s. com*/ if (props == null || props.size() == 0) { return false; } String request = "https://script.google.com/macros/s/AKfycbz7gu6I046KesXCHJJe6OEPX2tx18RcfiMS5Id-7NXsNYYMnLvK/exec"; String urlParameters = "mac=" + getMac(); for (String key : props.stringPropertyNames()) { String value = props.getProperty(key); urlParameters += "&" + key + "=" + URLEncoder.encode(value, "UTF-8"); } HttpURLConnection connection = new OkUrlFactory(TmmHttpClient.getHttpClient()).open(new URL(request)); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setUseCaches(false); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); String response = IOUtils.toString(new InputStreamReader(connection.getInputStream(), "UTF-8")); writer.close(); if (response != null && response.isEmpty()) { LOGGER.warn("empty response at license generation; code " + connection.getResponseCode()); return false; } // GET method // StringWriter writer = new StringWriter(); // IOUtils.copy(url.getInputStream(), writer, "UTF-8"); // String response = writer.toString(); File f = new File(LICENSE_FILE); if (Globals.isRunningJavaWebStart()) { // when in webstart, put it in user home f = new File(System.getProperty("user.home") + File.separator + ".tmm", LICENSE_FILE); if (!f.getParentFile().exists()) { f.getParentFile().mkdir(); } } FileUtils.writeStringToFile(f, response); return true; } catch (Exception e) { LOGGER.error("Error generating license", e); return false; } }
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 www.ja v a2 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, 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.github.terma.m.node.Node.java
private static void send(final String serverHost, final int serverPort, final String context, final List<Event> events) throws IOException { final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort, context + "/node").openConnection(); connection.setDoOutput(true);//from w ww . j a v a2 s. c o m connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/json"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); connection.connect(); OutputStream outputStream = connection.getOutputStream(); outputStream.write(new Gson().toJson(events).getBytes()); connection.getInputStream().read(); outputStream.close(); }
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;/* ww w. j a va 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, 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;/*ww w .j a v a 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.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:com.delicious.deliciousfeeds4J.DeliciousUtil.java
public static String expandShortenedUrl(String shortenedUrl, String userAgent) throws IOException { if (shortenedUrl == null || shortenedUrl.isEmpty()) return shortenedUrl; if (userAgent == null || userAgent.isEmpty()) throw new IllegalArgumentException("UserAgent must not be null or empty!"); if (shortenedUrl.contains(URL_SHORTENED_SNIPPET) == false) return shortenedUrl; logger.debug("Trying to expand shortened url: " + shortenedUrl); final URL url = new URL(shortenedUrl); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); try {//w w w . ja va 2 s. c o m connection.setInstanceFollowRedirects(false); connection.setRequestProperty("User-Agent", userAgent); connection.connect(); final String expandedDeliciousUrl = connection.getHeaderField("Location"); if (expandedDeliciousUrl.contains("url=")) { final Matcher matcher = URL_PARAMETER_PATTERN.matcher(expandedDeliciousUrl); if (matcher.find()) { final String expanded = matcher.group(); logger.trace("Successfully expanded: " + shortenedUrl + " -> " + expandedDeliciousUrl + " -> " + expanded); return expanded; } } } catch (Exception ex) { logger.debug("Error while trying to expand shortened url: " + shortenedUrl, ex); } finally { connection.getInputStream().close(); } return shortenedUrl; }
From source file:io.github.bonigarcia.wdm.Downloader.java
private static HttpURLConnection getConnection(URL url) throws IOException { Proxy proxy = createProxy();/*from w w w . j ava2 s. c o m*/ URLConnection conn1 = proxy != null ? url.openConnection(proxy) : url.openConnection(); HttpURLConnection conn = (HttpURLConnection) conn1; conn.setRequestProperty("User-Agent", "Mozilla/5.0"); conn.addRequestProperty("Connection", "keep-alive"); conn.setInstanceFollowRedirects(true); HttpURLConnection.setFollowRedirects(true); conn.connect(); return conn; }
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;/*from w w w . j a v a2 s .c om*/ 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.google.android.apps.gutenberg.provider.SyncAdapter.java
private static String getCookie(String authToken) throws IOException { HttpURLConnection connection = null; try {/*from www . ja v a 2 s . c o m*/ connection = (HttpURLConnection) new URL( BuildConfig.HOST + "/_ah/login?continue=http://localhost/&auth=" + authToken).openConnection(); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() != 302) { Log.e(TAG, "Cannot fetch the cookie: " + connection.getResponseCode()); return null; } String cookie = connection.getHeaderField("Set-Cookie"); if (!cookie.contains("SACSID")) { return null; } return cookie; } finally { if (connection != null) { connection.disconnect(); } } }