List of usage examples for java.net HttpURLConnection setFollowRedirects
public static void setFollowRedirects(boolean set)
From source file:com.vuze.android.remote.AndroidUtils.java
private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) { try {/*www. j av a 2 s .c om*/ HttpURLConnection.setFollowRedirects(false); URL url = new URL(URLName); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con instanceof HttpsURLConnection) { HttpsURLConnection conHttps = (HttpsURLConnection) con; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); conHttps.setSSLSocketFactory(ctx.getSocketFactory()); } conHttps.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } con.setConnectTimeout(conTimeout); con.setReadTimeout(readTimeout); con.setRequestMethod("HEAD"); con.getResponseCode(); if (DEBUG) { Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage()); } return true; } catch (Exception e) { if (DEBUG) { Log.e(TAG, "isLive " + URLName, e); } return false; } }
From source file:org.sakaiproject.portlets.PortletIFrame.java
public boolean popupXFrame(RenderRequest request, Placement placement, String url) { if (xframeCache < 1) return false; // Only check http:// and https:// urls if (!(url.startsWith("http://") || url.startsWith("https://"))) return false; // Check the "Always POPUP" and "Always INLINE" regular expressions String pattern = null;// w w w .ja v a 2 s . c o m Pattern p = null; Matcher m = null; pattern = ServerConfigurationService.getString(IFRAME_XFRAME_POPUP, null); if (pattern != null && pattern.length() > 1) { p = Pattern.compile(pattern); m = p.matcher(url.toLowerCase()); if (m.find()) { return true; } } pattern = ServerConfigurationService.getString(IFRAME_XFRAME_INLINE, null); if (pattern != null && pattern.length() > 1) { p = Pattern.compile(pattern); m = p.matcher(url.toLowerCase()); if (m.find()) { return false; } } // Don't check Local URLs String serverUrl = ServerConfigurationService.getServerUrl(); if (url.startsWith(serverUrl)) return false; if (url.startsWith(ServerConfigurationService.getAccessUrl())) return false; // Force http:// to pop-up if we are https:// if (request.isSecure() || (serverUrl != null && serverUrl.startsWith("https://"))) { if (url.startsWith("http://")) return true; } // Check to see if time has expired... Date date = new Date(); long nowTime = date.getTime(); String lastTimeS = placement.getPlacementConfig().getProperty(XFRAME_LAST_TIME); long lastTime = -1; try { lastTime = Long.parseLong(lastTimeS); } catch (NumberFormatException nfe) { lastTime = -1; } M_log.debug("lastTime=" + lastTime + " nowTime=" + nowTime); if (lastTime > 0 && nowTime < lastTime + xframeCache) { String lastXF = placement.getPlacementConfig().getProperty(XFRAME_LAST_STATUS); M_log.debug("Status from placement=" + lastXF); return "true".equals(lastXF); } placement.getPlacementConfig().setProperty(XFRAME_LAST_TIME, String.valueOf(nowTime)); boolean retval = false; try { // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection.setFollowRedirects(true); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); Map headerfields = con.getHeaderFields(); Set headers = headerfields.entrySet(); for (Iterator i = headers.iterator(); i.hasNext();) { Map.Entry map = (Map.Entry) i.next(); String key = (String) map.getKey(); if (key == null) continue; key = key.toLowerCase(); if (!"x-frame-options".equals(key)) continue; // Since the valid entries are SAMEORIGIN, DENY, or ALLOW-URI // we can pretty much assume the answer is "not us" if the header // is present retval = true; break; } } catch (Exception e) { // Fail pretty silently because this could be pretty chatty with bad urls and all M_log.debug(e.getMessage()); retval = false; } placement.getPlacementConfig().setProperty(XFRAME_LAST_STATUS, String.valueOf(retval)); // Permanently set popup to true as we don't expect that a site will go back if (retval == true) placement.getPlacementConfig().setProperty(POPUP, "true"); placement.save(); M_log.debug("Retrieved=" + url + " XFrame=" + retval); return retval; }
From source file:RhodesService.java
public static boolean pingHost(String host) { HttpURLConnection conn = null; boolean hostExists = false; try {/* w ww. j a va 2 s .c o m*/ URL url = new URL(host); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setAllowUserInteraction(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); hostExists = (conn.getContentLength() > 0); if (hostExists) Logger.I(TAG, "PING network SUCCEEDED."); else Logger.E(TAG, "PING network FAILED."); } catch (Exception e) { Logger.E(TAG, e); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception e) { Logger.E(TAG, e); } } } return hostExists; }
From source file:tvhchgen.Service.java
/** * Save the content of the Url to the given path * @param urlStr/*from w ww.ja v a 2 s . co m*/ * @param outPath * @return */ public boolean saveUrl(String urlStr, String outPath) { InputStream is = null; try { //System.out.println( "Getting: " + urlStr ); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); // allow both GZip and Deflate (ZLib) encodings conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT); conn.setRequestProperty("Referer", DEFAULT_REFERER); String encoding = conn.getContentEncoding(); InputStream inStr; // create the appropriate stream wrapper based on // the encoding type if (encoding != null && encoding.equalsIgnoreCase("gzip")) { inStr = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } else { inStr = conn.getInputStream(); } //System.out.println( filePath ); File file = new File(outPath); if (!file.exists()) { file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); ReadableByteChannel rbc = Channels.newChannel(inStr); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); return true; } } catch (Exception e) { System.out.println("Exception: " + e.toString()); } finally { if (is != null) { try { is.close(); } catch (Exception e) { System.out.println("Exception: " + e.toString()); } } } return false; }
From source file:org.opencms.staticexport.CmsAfterPublishStaticExportHandler.java
/** * Exports a single (template) resource specified by its export data.<p> * //from w ww . j a v a 2 s.co m * @param data the export data * @param cookies cookies to keep the session * * @return the status of the http request used to perform the export * * @throws IOException if the http request fails */ protected int exportTemplateResource(CmsStaticExportData data, StringBuffer cookies) throws IOException { String vfsName = data.getVfsName(); String rfsName = data.getRfsName(); CmsStaticExportManager manager = OpenCms.getStaticExportManager(); String exportUrlStr; if (rfsName.contains(manager.getRfsPrefix(vfsName))) { LOG.info("rfsName " + rfsName + " contains rfsPrefix " + manager.getRfsPrefix(vfsName)); exportUrlStr = manager.getExportUrl() + rfsName; } else { exportUrlStr = manager.getExportUrl() + manager.getRfsPrefix(vfsName) + rfsName; } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SENDING_REQUEST_2, rfsName, exportUrlStr)); } // setup the connection and request the resource URL exportUrl = new URL(exportUrlStr); HttpURLConnection.setFollowRedirects(false); HttpURLConnection urlcon = (HttpURLConnection) exportUrl.openConnection(); // set request type to GET urlcon.setRequestMethod(REQUEST_METHOD_GET); // add special export header urlcon.setRequestProperty(CmsRequestUtil.HEADER_OPENCMS_EXPORT, CmsStringUtil.TRUE); // add additional headers if available if (manager.getAcceptLanguageHeader() != null) { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_LANGUAGE, manager.getAcceptLanguageHeader()); } else { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_LANGUAGE, manager.getDefaultAcceptLanguageHeader()); } if (manager.getAcceptCharsetHeader() != null) { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_CHARSET, manager.getAcceptCharsetHeader()); } else { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_CHARSET, manager.getDefaultAcceptCharsetHeader()); } // get the last modified date and add it to the request String exportFileName = CmsFileUtil.normalizePath(manager.getExportPath(vfsName) + rfsName); File exportFile = new File(exportFileName); long dateLastModified = exportFile.lastModified(); // system folder case if (vfsName.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) { // iterate over all rules Iterator<CmsStaticExportRfsRule> it = manager.getRfsRules().iterator(); while (it.hasNext()) { CmsStaticExportRfsRule rule = it.next(); if (rule.match(vfsName)) { exportFileName = CmsFileUtil.normalizePath(rule.getExportPath() + rfsName); exportFile = new File(exportFileName); if (dateLastModified > exportFile.lastModified()) { dateLastModified = exportFile.lastModified(); } } } } urlcon.setIfModifiedSince(dateLastModified); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_IF_MODIFIED_SINCE_SET_2, exportFile.getName(), new Long((dateLastModified / 1000) * 1000))); } if (cookies.length() > 0) { // set the cookies, included the session id to keep the same session urlcon.setRequestProperty(REQUEST_PROPERTY_COOKIE, cookies.toString()); } // now perform the request urlcon.connect(); int status = urlcon.getResponseCode(); if (cookies.length() == 0) { //Now retrieve the cookies. The jsessionid is here cookies.append(urlcon.getHeaderField(HEADER_FIELD_SET_COOKIE)); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_STATICEXPORT_COOKIES_1, cookies)); } } urlcon.disconnect(); if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_REQUEST_RESULT_3, rfsName, exportUrlStr, new Integer(status))); } return status; }
From source file:iracing.webapi.IracingWebApi.java
private boolean forumLoginAndGetCookie() { try {/* w w w .j av a 2 s .c o m*/ // Make a connect to the server URL url = new URL(FORUM_LOGIN_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty(COOKIE, cookie); conn.setDoInput(true); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); HttpURLConnection.setFollowRedirects(false); conn.connect(); if (isMaintenancePage(conn)) return false; String headerName; boolean containsCookie = false; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equalsIgnoreCase(SET_COOKIE)) { containsCookie = true; addToCookieMap(conn.getHeaderField(i)); } } if (containsCookie) createCookieFromMap(); conn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
From source file:it.evilsocket.dsploit.core.UpdateService.java
/** * download mCurrentTask.url to mCurrentTask.path * * @throws KeyException when MD5 or SHA1 sum fails * @throws IOException when IOError occurs * @throws NoSuchAlgorithmException when required digest algorithm is not available * @throws CancellationException when user cancelled the download via notification */// w w w .j a v a2 s .co m private void downloadFile() throws SecurityException, KeyException, IOException, NoSuchAlgorithmException, CancellationException { if (mCurrentTask.url == null || mCurrentTask.path == null) return; File file = null; FileOutputStream writer = null; InputStream reader = null; HttpURLConnection connection = null; boolean exitForError = true; try { MessageDigest md5, sha1; URL url; byte[] buffer; int read; short percentage, previous_percentage; long downloaded, total; mBuilder.setContentTitle(getString(R.string.downloading_update)) .setContentText(getString(R.string.connecting)) .setSmallIcon(android.R.drawable.stat_sys_download).setProgress(100, 0, true); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); md5 = (mCurrentTask.md5 != null ? MessageDigest.getInstance("MD5") : null); sha1 = (mCurrentTask.sha1 != null ? MessageDigest.getInstance("SHA-1") : null); buffer = new byte[4096]; file = new File(mCurrentTask.path); if (file.exists() && file.isFile()) //noinspection ResultOfMethodCallIgnored file.delete(); HttpURLConnection.setFollowRedirects(true); url = new URL(mCurrentTask.url); connection = (HttpURLConnection) url.openConnection(); connection.connect(); writer = new FileOutputStream(file); reader = connection.getInputStream(); total = connection.getContentLength(); read = connection.getResponseCode(); if (read != 200) throw new IOException( String.format("cannot download '%s': responseCode: %d", mCurrentTask.url, read)); downloaded = 0; previous_percentage = -1; mBuilder.setContentText(file.getName()); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); Logger.info(String.format("downloading '%s' to '%s'", mCurrentTask.url, mCurrentTask.path)); while (mRunning && (read = reader.read(buffer)) != -1) { writer.write(buffer, 0, read); if (md5 != null) md5.update(buffer, 0, read); if (sha1 != null) sha1.update(buffer, 0, read); if (total >= 0) { downloaded += read; percentage = (short) (((double) downloaded / total) * 100); if (percentage != previous_percentage) { mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%"); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); previous_percentage = percentage; } } } if (!mRunning) throw new CancellationException("download cancelled"); Logger.info("download finished successfully"); if (md5 != null || sha1 != null) { if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest()))) { throw new KeyException("wrong MD5"); } else if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest()))) { throw new KeyException("wrong SHA-1"); } } else if (mCurrentTask.archiver != null) { verifyArchiveIntegrity(); } exitForError = false; } finally { if (exitForError && file != null && file.exists() && !file.delete()) Logger.error(String.format("cannot delete file '%s'", mCurrentTask.path)); try { if (writer != null) writer.close(); if (reader != null) reader.close(); if (connection != null) connection.disconnect(); } catch (IOException e) { System.errorLogging(e); } } }
From source file:com.BeatYourRecord.SubmitActivity.java
private ResumeInfo resumeFileUpload(String uploadUrl) throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException { HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestProperty("Content-Range", "bytes */*"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); urlConnection.setFixedLengthStreamingMode(0); HttpURLConnection.setFollowRedirects(false); urlConnection.connect();/*from w w w. ja v a 2 s . c o m*/ int responseCode = urlConnection.getResponseCode(); if (responseCode >= 300 && responseCode < 400) { int nextByteToUpload; String range = urlConnection.getHeaderField("Range"); if (range == null) { Log.d(LOG_TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl)); nextByteToUpload = 0; } else { Log.d(LOG_TAG, String.format("Range header is '%s'.", range)); String[] parts = range.split("-"); if (parts.length > 1) { nextByteToUpload = Integer.parseInt(parts[1]) + 1; } else { nextByteToUpload = 0; } } return new ResumeInfo(nextByteToUpload); } else if (responseCode >= 200 && responseCode < 300) { return new ResumeInfo(parseVideoId(urlConnection.getInputStream())); } else if (responseCode == 500) { // TODO this is a workaround for current problems with resuming uploads while switching transport (Wifi->EDGE) throw new Internal500ResumeException( String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } else { throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } }
From source file:com.codename1.impl.android.AndroidImplementation.java
@Override public void init(Object m) { if (m instanceof CodenameOneActivity) { setContext(null);/*from w ww . ja va 2 s .c o m*/ setActivity((CodenameOneActivity) m); } else { setActivity(null); setContext((Context) m); } instance = this; if (getActivity() != null && getActivity().hasUI()) { if (!hasActionBar()) { try { getActivity().requestWindowFeature(Window.FEATURE_NO_TITLE); } catch (Exception e) { //Log.d("Codename One", "No idea why this throws a Runtime Error", e); } } else { getActivity().invalidateOptionsMenu(); try { getActivity().requestWindowFeature(Window.FEATURE_ACTION_BAR); getActivity().requestWindowFeature(Window.FEATURE_PROGRESS); if (android.os.Build.VERSION.SDK_INT >= 21) { //WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS getActivity().getWindow().addFlags(-2147483648); } } catch (Exception e) { //Log.d("Codename One", "No idea why this throws a Runtime Error", e); } NotifyActionBar notify = new NotifyActionBar(getActivity(), false); notify.run(); } if (statusBarHidden) { getActivity().getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); getActivity().getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT); } if (Display.getInstance().getProperty("StatusbarHidden", "").equals("true")) { getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (Display.getInstance().getProperty("KeepScreenOn", "").equals("true")) { getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } if (Display.getInstance().getProperty("DisableScreenshots", "").equals("true")) { getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } if (m instanceof CodenameOneActivity) { ((CodenameOneActivity) m).setDefaultIntentResultListener(this); ((CodenameOneActivity) m).setIntentResultListener(this); } /** * translate our default font height depending on the screen density. * this is required for new high resolution devices. otherwise * everything looks awfully small. * * we use our default font height value of 16 and go from there. i * thought about using new Paint().getTextSize() for this value but if * some new version of android suddenly returns values already tranlated * to the screen then we might end up with too large fonts. the * documentation is not very precise on that. */ final int defaultFontPixelHeight = 16; this.defaultFontHeight = this.translatePixelForDPI(defaultFontPixelHeight); this.defaultFont = (CodenameOneTextPaint) ((NativeFont) this.createFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM)).font; Display.getInstance().setTransitionYield(-1); initSurface(); /** * devices are extremely sensitive so dragging should start a little * later than suggested by default implementation. */ this.setDragStartPercentage(1); VirtualKeyboardInterface vkb = new AndroidKeyboard(this); Display.getInstance().registerVirtualKeyboard(vkb); Display.getInstance().setDefaultVirtualKeyboard(vkb); InPlaceEditView.endEdit(); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if (nativePeers.size() > 0) { for (int i = 0; i < nativePeers.size(); i++) { ((AndroidImplementation.AndroidPeer) nativePeers.elementAt(i)).init(); } } } else { /** * translate our default font height depending on the screen density. * this is required for new high resolution devices. otherwise * everything looks awfully small. * * we use our default font height value of 16 and go from there. i * thought about using new Paint().getTextSize() for this value but if * some new version of android suddenly returns values already tranlated * to the screen then we might end up with too large fonts. the * documentation is not very precise on that. */ final int defaultFontPixelHeight = 16; this.defaultFontHeight = this.translatePixelForDPI(defaultFontPixelHeight); this.defaultFont = (CodenameOneTextPaint) ((NativeFont) this.createFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM)).font; } HttpURLConnection.setFollowRedirects(false); CookieHandler.setDefault(null); }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private ResumeInfo resumeFileUpload(String uploadUrl) throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException { HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestProperty("Content-Range", "bytes */*"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); urlConnection.setFixedLengthStreamingMode(0); HttpURLConnection.setFollowRedirects(false); urlConnection.connect();//w ww.j ava2 s. co m int responseCode = urlConnection.getResponseCode(); if (responseCode >= 300 && responseCode < 400) { int nextByteToUpload; String range = urlConnection.getHeaderField("Range"); if (range == null) { Log.d(TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl)); nextByteToUpload = 0; } else { Log.d(TAG, String.format("Range header is '%s'.", range)); String[] parts = range.split("-"); if (parts.length > 1) { nextByteToUpload = Integer.parseInt(parts[1]) + 1; } else { nextByteToUpload = 0; } } return new ResumeInfo(nextByteToUpload); } else if (responseCode >= 200 && responseCode < 300) { return new ResumeInfo(parseVideoId(urlConnection.getInputStream())); } else if (responseCode == 500) { // TODO this is a workaround for current problems with resuming // uploads while switching transport (Wifi->EDGE) throw new Internal500ResumeException( String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } else { throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } }