List of usage examples for java.net URLConnection connect
public abstract void connect() throws IOException;
From source file:servlet.GetCity.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja v a 2s. c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public String getData(String urlString) { String result = ""; BufferedReader read = null; try { URL realurl = new URL(urlString); URLConnection connection = realurl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.connect(); Map<String, List<String>> map = connection.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; while ((line = read.readLine()) != null) { result += line; } } catch (IOException e) { e.printStackTrace(); } finally { if (read != null) { try { read.close(); } catch (Exception e) { e.printStackTrace(); } } } return result; }
From source file:org.pentaho.webpackage.deployer.archive.impl.WebPackageURLConnection.java
@Override public InputStream getInputStream() throws IOException { try {/* www.j av a 2 s . c om*/ final PipedOutputStream pipedOutputStream = new PipedOutputStream(); PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); // making this here allows to fail with invalid URLs final java.net.URLConnection urlConnection = this.url.openConnection(); urlConnection.connect(); final InputStream originalInputStream = urlConnection.getInputStream(); this.transform_thread = EXECUTOR .submit(new WebPackageTransformer(this.url, originalInputStream, pipedOutputStream)); return pipedInputStream; } catch (Exception e) { this.logger.error(getURL().toString() + ": Error opening url"); throw new IOException("Error opening url", e); } }
From source file:org.silverpeas.mobile.server.servlets.PublicationContentServlet.java
private String convertSpImageUrlToDataUrl(String url) { String data = url;// ww w .j av a 2 s. co m if (url.contains("GalleryInWysiwyg")) { try { String instanceId = url.substring(url.indexOf("ComponentId") + "ComponentId".length() + 1); instanceId = instanceId.substring(0, instanceId.indexOf("&")); String imageId = url.substring(url.indexOf("ImageId") + "ImageId".length() + 1); imageId = imageId.substring(0, imageId.indexOf("&")); Photo photo = getGalleryService().getPhoto(new MediaPK(imageId)); String[] rep = { "image" + imageId }; String path = FileRepositoryManager.getAbsolutePath(null, instanceId, rep); File f = new File(path + photo.getFileName()); FileInputStream is = new FileInputStream(f); byte[] binaryData = new byte[(int) f.length()]; is.read(binaryData); is.close(); data = "data:" + photo.getFileMimeType() + ";base64," + new String(Base64.encodeBase64(binaryData)); } catch (Exception e) { SilverLogger.getLogger(SpMobileLogModule.getName()) .error("PublicationContentServlet.convertSpImageUrlToDataUrl", "root.EX_NO_MESSAGE", e); } } else if (url.contains("attachmentId")) { data = convertImageAttachmentUrl(url, data); } else { try { if (url.startsWith("/silverpeas")) { url = rootContext + url; } URL urlObject = new URL(url); URLConnection connection = urlObject.openConnection(); connection.connect(); String contentType = connection.getContentType(); byte[] binaryData = new byte[(int) connection.getInputStream().available()]; connection.getInputStream().read(binaryData); data = "data:" + contentType + ";base64," + new String(Base64.encodeBase64(binaryData)); } catch (Exception e) { SilverLogger.getLogger(SpMobileLogModule.getName()) .error("PublicationContentServlet.convertImageUrlToDataUrl", "root.EX_NO_MESSAGE", e); // If can't connect to url, return the url without change } } return data; }
From source file:org.squale.welcom.outils.WelcomConfigurator.java
/** * Initialise les proprits du fichier de configuration - lastDate - isGoodResources * //from ww w .j a va 2 s . c o m * @param pFileName fichier de configuration */ private void initializeFile(final String pFileName) { String realFileName = ""; this.fileName = pFileName; InputStream is = null; if (!GenericValidator.isBlankOrNull(fileName)) { // Set up to load the property resource for this locale key, if we can realFileName = fileName.replace('.', '/') + ".properties"; goodFileResources = true; final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Recherche la date de derniere modification final URL url = classLoader.getResource(realFileName); URLConnection urlConn; try { urlConn = url.openConnection(); urlConn.setUseCaches(false); urlConn.connect(); urlConn.getLastModified(); lastDateFile = new Date(urlConn.getLastModified()); } catch (final Exception e) { goodFileResources = false; } // Regarde si le fichier n'est pas vide is = classLoader.getResourceAsStream(realFileName); goodFileResources = (is != null); } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java
@Test() public void withAuthenticator() throws Exception { assertEquals("Unexpected calls to password provider", 0, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); // Set the authenticator to our Credential Manager-backed one that also // counts calls to itself CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager); assertEquals("Unexpected calls to authenticator", 0, authenticator.calls); Authenticator.setDefault(authenticator); // FixedPasswordProvider.setUsernamePassword(new UsernamePassword( // USERNAME, PASSWORD)); URL url = new URL("http://localhost:" + PORT + "/test.html"); httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD)); URLConnection c = url.openConnection(); c.connect(); try {/* w ww . j a v a 2 s.c om*/ c.getContent(); } catch (Exception ex) { } System.out.println(c.getHeaderField(0)); assertEquals("Did not invoke authenticator", 1, authenticator.calls); assertEquals("Did not invoke our password provider", 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0)); assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage()); assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString()); // And test Java's cache: URLConnection c2 = url.openConnection(); c2.connect(); assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0)); assertEquals("JVM invoked our authenticator again instead of caching", 1, authenticator.calls); assertEquals("Invoked our password provider again instead of caching", 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java
@Test() public void withAuthenticatorResetJava() throws Exception { assertTrue("Could not reset JVMs authCache, ignore on non-Sun JVM", credentialManager.resetAuthCache()); assertEquals("Unexpected calls to password provider", 0, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); CountingAuthenticator authenticator = new CountingAuthenticator(credentialManager); assertEquals("Unexpected calls to authenticator", 0, authenticator.calls); Authenticator.setDefault(authenticator); // FixedPasswordProvider.setUsernamePassword(new UsernamePassword( // USERNAME, PASSWORD)); URL url = new URL("http://localhost:" + PORT + "/test.html"); httpAuthProvider.setServiceUsernameAndPassword(url.toURI(), new UsernamePassword(USERNAME, PASSWORD)); URLConnection c = url.openConnection(); c.connect(); try {/*w w w .j a v a 2 s. co m*/ c.getContent(); } catch (Exception ex) { } assertEquals("HTTP/1.1 200 OK", c.getHeaderField(0)); assertEquals("Did not invoke authenticator", 1, authenticator.calls); assertEquals("Did not invoke our password provider", 1, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); assertEquals("Unexpected prompt/realm", REALM, httpAuthProvider.getRequestMessage()); assertEquals("Unexpected URI", url.toURI().toASCIIString() + "#" + REALM, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getServiceURI().toASCIIString()); // And without Java's cache: assertTrue("Could not reset VMs authCache, ignore on non-Sun VM", credentialManager.resetAuthCache()); URLConnection c2 = url.openConnection(); c2.connect(); assertEquals("HTTP/1.1 200 OK", c2.getHeaderField(0)); assertEquals("Did not invoke our authenticator again", 2, authenticator.calls); assertEquals("Did not invoke our password provider again", 2, HTTPAuthenticatorServiceUsernameAndPasswordProvider.getCalls()); }
From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java
@Override public BinaryContent getData(String urlStr) throws IOException { URL url = new URL(urlStr); URLConnection conn = url.openConnection(); if (conn instanceof HttpsURLConnection) { try {/* www.j a v a 2 s . c o m*/ ((HttpsURLConnection) conn).setSSLSocketFactory(getSocketFactory()); } catch (Exception e) { throw new IOException("Error in creating SSL socket.", e); } } conn.connect(); MimeType mimeType = DEFAULT_MIMETYPE; try { mimeType = new MimeType(conn.getContentType()); } catch (MimeTypeParseException e) { LOGGER.debug("Error creating mime type with input [" + conn.getContentType() + "], defaulting to " + DEFAULT_MIMETYPE.toString()); } return new BinaryContentImpl(conn.getInputStream(), mimeType); }
From source file:org.jahia.utils.maven.plugin.TestMojo.java
private void executeAllTests() { try {/*from w w w . j ava 2 s.com*/ List<String> targets = new ArrayList<String>(); String url1 = testURL + "/test" + (StringUtils.isNotEmpty(test) ? "/" + test : ""); if (skipCoreTests) { url1 += "?skipCoreTests=true"; } getLog().info("Get tests from : " + url1); URLConnection conn = null; if (startupWait) { getLog().info("Waiting for jahia startup"); for (int i = startupTimeout; i > 0; i--) { try { conn = new URL(url1).openConnection(); conn.connect(); break; } catch (IOException e) { try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.print("."); } } } else { conn = new URL(url1).openConnection(); } InputStream is = null; if (conn != null) { is = conn.getInputStream(); } BufferedReader r = new BufferedReader(new InputStreamReader(is)); String line; while ((line = r.readLine()) != null) { getLog().info("Adding test " + line); targets.add(line); } if (is != null) { is.close(); } long timer = System.currentTimeMillis(); getLog().info("Start executing all tests (" + targets.size() + ")..."); for (String s : targets) { executeTest(s, false); } getLog().info("...done in " + (System.currentTimeMillis() - timer) / 1000 + " s"); } catch (IOException e) { getLog().error(e); } }
From source file:uk.co.tekkies.readings.activity.ReadingsActivity.java
private String backgroundDownloadNewsToast(String versionName) { String summary = null;/*from ww w.j a v a 2s . com*/ URL url; try { //Append version, so we can easily prompt users to upgrade, if necessary. url = new URL(NEWS_TOAST_URL + "?v=" + versionName); URLConnection connection = url.openConnection(); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); //Sanity check message: e.g. We wouldn't want to toast html from a hotspot paywall if (line != null) { if (line.equals("uk.co.tekkies.readings.news-toast")) { line = reader.readLine(); summary = ""; while (line != null) { summary += line + "\n"; line = reader.readLine(); } } } reader.close(); } catch (UnknownHostException e) { //swallow it } catch (ConnectException e) { //swallow it } catch (SocketException e) { //swallow it } catch (FileNotFoundException e) { //swallow it } catch (SocketTimeoutException e) { //swallow it } catch (Exception e) { Analytics.reportCaughtException(this, e); } return summary; }
From source file:net.sf.taverna.t2.activities.wsdl.WSDLActivity.java
private void parseWSDL() throws ParserConfigurationException, WSDLException, IOException, SAXException, UnknownOperationException {// w ww.j a v a 2 s .c om String wsdlLocation = configurationBean.get("operation").get("wsdl").textValue(); URLConnection connection = null; try { URL wsdlURL = new URL(wsdlLocation); connection = wsdlURL.openConnection(); connection.setConnectTimeout(RemoteHealthChecker.getTimeoutInSeconds() * 1000); connection.connect(); } catch (MalformedURLException e) { throw new IOException("Malformed URL", e); } catch (SocketTimeoutException e) { throw new IOException("Timeout", e); } catch (IOException e) { throw e; } finally { if ((connection != null) && (connection.getInputStream() != null)) { connection.getInputStream().close(); } } parser = new WSDLParser(wsdlLocation); isWsrfService = parser.isWsrfService(); }