List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:eu.eubrazilcc.lvl.oauth2.AuthTest.java
private static HttpURLConnection doRequest(final OAuthClientRequest request) throws IOException { final URL url = new URL(request.getLocationUri()); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(true); conn.connect(); conn.getResponseCode();//from ww w. j a v a 2 s. c om return conn; }
From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java
public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) { // cache ? ?. String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl); //System.out.println("getContentTypeFromCache : " + result); if (StringUtils.isNotEmpty(result)) { return result; }/*from w ww . j av a2 s . c o m*/ HttpURLConnection con = null; try { URL url = new URL(strUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); con.setConnectTimeout(1000); con.setReadTimeout(1000); con.connect(); int resCode = con.getResponseCode(); if (resCode != HttpURLConnection.HTTP_OK) { System.err.println("error"); } else { result = con.getContentType(); //System.out.println("content-type from response header: " + result); if (result != null) { contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date())); } } } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } return result; }
From source file:io.github.bonigarcia.wdm.Downloader.java
private static HttpURLConnection getConnection(URL url) throws IOException { Proxy proxy = createProxy();//from w ww. j a va2 s .c om 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:net.doubledoordev.cmd.CurseModpackDownloader.java
public static String getFinalURL(String url) throws IOException { while (true) { HttpURLConnection con = null; try {/* ww w . j a v a2s. c o m*/ con = (HttpURLConnection) new URL(url).openConnection(); con.setInstanceFollowRedirects(false); con.connect(); if (con.getHeaderField("Location") == null) return url; url = con.getHeaderField("Location"); } catch (IOException e) { return url; } finally { if (con != null) con.disconnect(); } } }
From source file:Main.java
public static String customrequest(String url, HashMap<String, String> params, String method) { try {/*from w w w. ja v a2 s . c o m*/ URL postUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); conn.connect(); OutputStream out = conn.getOutputStream(); StringBuilder sb = new StringBuilder(); if (null != params) { int i = params.size(); for (Map.Entry<String, String> entry : params.entrySet()) { if (i == 1) { sb.append(entry.getKey() + "=" + entry.getValue()); } else { sb.append(entry.getKey() + "=" + entry.getValue() + "&"); } i--; } } String content = sb.toString(); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); InputStream inStream = conn.getInputStream(); String result = inputStream2String(inStream); conn.disconnect(); return result; } catch (Exception e) { // TODO: handle exception } 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;/*w w w .j a v a 2 s. c om*/ 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:website.openeng.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {//www .j ava2s . co m try { URL url = new URL(UrlToFile); String extension = UrlToFile.substring(UrlToFile.length() - 4); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Referer", "website.openeng.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(60000); urlConnection.connect(); File file = File.createTempFile(prefix, extension, context.getCacheDir()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); return file.getAbsolutePath(); } catch (Exception e) { return "FAILED " + e.getMessage(); } }
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 {/*from w w w . ja v a2 s. co 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:LNISmokeTest.java
/** * Get an item with WebDAV GET http request. * /* w ww .j a v a 2 s .com*/ * @param lni the lni * @param itemHandle the item handle * @param packager the packager * @param output the output * @param endpoint the endpoint * * @throws RemoteException the remote exception * @throws ProtocolException the protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception */ private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output, String endpoint) throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException { // assemble URL from chopped endpoint-URL and relative URI String itemURI = doLookup(lni, itemHandle, null); URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager); System.err.println("DEBUG: GET from URL: " + url.toString()); // connect with GET method, then copy file over. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); fixBasicAuth(url, conn); conn.connect(); int status = conn.getResponseCode(); if (status < 200 || status >= 300) { die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage()); } InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(output); copyStream(in, out); in.close(); out.close(); System.err.println("DEBUG: Created local file " + output); System.err.println( "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage()); }
From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBlockchainInfo() { try {//from w w w .j av a 2 s .c o m Double btcRate = 0.0; Object result = getCoinValueBTC(); if (result == null) return null; else btcRate = (Double) result; final URL URL = new URL("https://blockchain.info/ticker"); final HttpURLConnection connection = (HttpURLConnection) URL.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return null; Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); final JSONObject o = head.getJSONObject(currencyCode); //final String rate = o.optString("15m", null); double rateForBTC = o.getDouble("15m") * btcRate; final String rate = String.format("%.8f", rateForBTC); //o.optString("15m", null); if (rate != null) { try { rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } catch (final ArithmeticException x) { log.debug("problem reading exchange rate: " + currencyCode, x); } } } return rates; } finally { if (reader != null) reader.close(); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } return null; }