List of usage examples for java.net URLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:de.anycook.social.facebook.FacebookHandler.java
@SuppressWarnings("unchecked") public static String publishtoWall(long facebookID, String accessToken, String message, String header) throws IOException { StringBuilder out = new StringBuilder(); StringBuilder data = new StringBuilder(); data.append("access_token=").append(URLEncoder.encode(accessToken, "UTF-8")); data.append("&message=").append(URLEncoder.encode(message, "UTF-8")); data.append("&name=").append(URLEncoder.encode(header, "UTF-8")); URL url = new URL("https://api.facebook.com/" + facebookID + "/feed"); URLConnection conn = url.openConnection(); conn.setDoOutput(true);//www .j av a2 s . c o m try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) { wr.write(data.toString()); wr.flush(); try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = rd.readLine()) != null) { out.append(line); } } } return out.toString(); }
From source file:me.fromgate.facechat.UpdateChecker.java
private static void updateLastVersion() { if (!enableUpdateChecker) return;//from www. jav a2 s .co m URL url = null; try { url = new URL(projectApiUrl); } catch (Exception e) { log("Failed to create URL: " + projectApiUrl); return; } try { URLConnection conn = url.openConnection(); conn.addRequestProperty("X-API-Key", null); conn.addRequestProperty("User-Agent", projectName + " using UpdateChecker (by fromgate)"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() > 0) { JSONObject latest = (JSONObject) array.get(array.size() - 1); String plugin_name = (String) latest.get("name"); projectLastVersion = plugin_name.replace(projectName + " v", "").trim(); } } catch (Exception e) { log("Failed to check last version"); } }
From source file:com.connectsdk.core.upnp.Device.java
public static Device createInstanceFromXML(String url, String searchTarget) { Device newDevice = null;/*from w w w. ja v a 2s . c om*/ try { newDevice = new Device(url, searchTarget); } catch (IOException e) { return null; } final Device device = newDevice; DefaultHandler dh = new DefaultHandler() { String currentValue = null; Icon currentIcon; Service currentService; @Override public void characters(char[] ch, int start, int length) throws SAXException { currentValue = new String(ch, start, length); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (Icon.TAG.equals(qName)) { currentIcon = new Icon(); } else if (Service.TAG.equals(qName)) { currentService = new Service(); currentService.baseURL = device.baseURL; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // System.out.println("[DEBUG] qName: " + qName + ", currentValue: " + currentValue); /* Parse device-specific information */ if (TAG_DEVICE_TYPE.equals(qName)) { device.deviceType = currentValue; } else if (TAG_FRIENDLY_NAME.equals(qName)) { device.friendlyName = currentValue; } else if (TAG_MANUFACTURER.equals(qName)) { device.manufacturer = currentValue; } else if (TAG_MANUFACTURER_URL.equals(qName)) { device.manufacturerURL = currentValue; } else if (TAG_MODEL_DESCRIPTION.equals(qName)) { device.modelDescription = currentValue; } else if (TAG_MODEL_NAME.equals(qName)) { device.modelName = currentValue; } else if (TAG_MODEL_NUMBER.equals(qName)) { device.modelNumber = currentValue; } else if (TAG_MODEL_URL.equals(qName)) { device.modelURL = currentValue; } else if (TAG_SERIAL_NUMBER.equals(qName)) { device.serialNumber = currentValue; } else if (TAG_UDN.equals(qName)) { device.UDN = currentValue; // device.UUID = Device.parseUUID(currentValue); } else if (TAG_UPC.equals(qName)) { device.UPC = currentValue; } /* Parse icon-list information */ else if (Icon.TAG_MIME_TYPE.equals(qName)) { currentIcon.mimetype = currentValue; } else if (Icon.TAG_WIDTH.equals(qName)) { currentIcon.width = currentValue; } else if (Icon.TAG_HEIGHT.equals(qName)) { currentIcon.height = currentValue; } else if (Icon.TAG_DEPTH.equals(qName)) { currentIcon.depth = currentValue; } else if (Icon.TAG_URL.equals(qName)) { currentIcon.url = currentValue; } else if (Icon.TAG.equals(qName)) { device.iconList.add(currentIcon); } /* Parse service-list information */ else if (Service.TAG_SERVICE_TYPE.equals(qName)) { currentService.serviceType = currentValue; } else if (Service.TAG_SERVICE_ID.equals(qName)) { currentService.serviceId = currentValue; } else if (Service.TAG_SCPD_URL.equals(qName)) { currentService.SCPDURL = currentValue; } else if (Service.TAG_CONTROL_URL.equals(qName)) { currentService.controlURL = currentValue; } else if (Service.TAG_EVENTSUB_URL.equals(qName)) { currentService.eventSubURL = currentValue; } else if (Service.TAG.equals(qName)) { device.serviceList.add(currentService); } } }; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser; try { URL mURL = new URL(url); URLConnection urlConnection = mURL.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); try { parser = factory.newSAXParser(); parser.parse(in, dh); } finally { in.close(); } device.headers = urlConnection.getHeaderFields(); return device; } catch (MalformedURLException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:test.ApplicationTest.java
static String call(final String request, final String contentType) { try {/*from w w w. j a v a 2 s .c o m*/ final URLConnection url = new URL("http://localhost:" + TEST_SERVER_PORT + "/" + request) .openConnection(); url.setRequestProperty("Accept", contentType); return CharStreams.toString(new InputStreamReader(url.getInputStream(), Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.moviejukebox.themoviedb.tools.WebBrowser.java
public static String request(URL url) throws MovieDbException { StringWriter content = null;/*w w w.j av a 2s . co m*/ try { content = new StringWriter(); BufferedReader in = null; URLConnection cnx = null; try { cnx = openProxiedConnection(url); sendHeader(cnx); readHeader(cnx); in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx))); String line; while ((line = in.readLine()) != null) { content.write(line); } } finally { if (in != null) { in.close(); } if (cnx instanceof HttpURLConnection) { ((HttpURLConnection) cnx).disconnect(); } } return content.toString(); } catch (IOException ex) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, ex); } finally { if (content != null) { try { content.close(); } catch (IOException ex) { LOGGER.debug("Failed to close connection: " + ex.getMessage()); } } } }
From source file:com.yoctopuce.YoctoAPI.YFirmwareUpdate.java
static byte[] _downloadfile(String url) throws YAPI_Exception { ByteArrayOutputStream result = new ByteArrayOutputStream(1024); URL u = null;//from w w w . j av a2 s . c o m try { u = new URL(url); } catch (MalformedURLException e) { throw new YAPI_Exception(YAPI.IO_ERROR, e.getLocalizedMessage()); } BufferedInputStream in = null; try { URLConnection connection = u.openConnection(); in = new BufferedInputStream(connection.getInputStream()); byte[] buffer = new byte[1024]; int readed = 0; while (readed >= 0) { readed = in.read(buffer, 0, buffer.length); if (readed < 0) { // end of connection break; } else { result.write(buffer, 0, readed); } } } catch (IOException e) { throw new YAPI_Exception(YAPI.IO_ERROR, "unable to contact www.yoctopuce.com :" + e.getLocalizedMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return result.toByteArray(); }
From source file:com.qweex.callisto.moar.twit.java
public static String callURL(String myURL) { StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;//from w w w . ja v a 2 s . c om try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) urlConn.setReadTimeout(60 * 1000); if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { throw new RuntimeException("Exception while calling URL:" + myURL, e); } return sb.toString(); }
From source file:fr.asso.vieillescharrues.parseurs.TelechargeFichier.java
/** * Mthode statique grant le tlechargement de fichiers * @param url Adresse du fichier// w w w . j av a2 s. co m * @param fichierDest Nom du ficher en local */ public static void DownloadFromUrl(URL url, String fichierDest) throws IOException { File file; if (fichierDest.endsWith(".jpg")) file = new File(PATH + "images/", fichierDest); else file = new File(PATH, fichierDest); file.getParentFile().mkdirs(); URLConnection ucon = url.openConnection(); try { tailleDistant = ucon.getHeaderFieldInt("Content-Length", 0); //Rcupre le header HTTP Content-Length tailleLocal = (int) file.length(); } catch (Exception e) { e.printStackTrace(); } // Compare les tailles des fichiers if ((tailleDistant == tailleLocal) && (tailleLocal != 0)) return; InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); }
From source file:com.bt.download.android.gui.transfers.HttpDownload.java
static void simpleHTTP(String url, OutputStream out, int timeout) throws Throwable { URL u = new URL(url); URLConnection con = u.openConnection(); con.setConnectTimeout(timeout);//from w ww . j a v a 2s . c o m con.setReadTimeout(timeout); InputStream in = con.getInputStream(); try { byte[] b = new byte[1024]; int n = 0; while ((n = in.read(b, 0, b.length)) != -1) { out.write(b, 0, n); } } finally { try { out.close(); } catch (Throwable e) { // ignore } try { in.close(); } catch (Throwable e) { // ignore } } }
From source file:edu.stanford.muse.webapp.Accounts.java
/** does account setup and login (and look up default folder if well-known account) from the given request. * request params are loginName<N>, password<N>, etc (see loginForm for details). * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure. * if success and account has a well-known sent mail folder, the returned object also has something like: * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033} * accounts on the login page are numbered 0 upwards. */ public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException { JSONObject result = new JSONObject(); HttpSession session = request.getSession(); // allocate the fetcher if it doesn't already exist MuseEmailFetcher m = null;/*from www . ja va 2 s .com*/ synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult. { m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher"); boolean doIncremental = request.getParameter("incremental") != null; if (m == null || !doIncremental) { m = new MuseEmailFetcher(); session.setAttribute("museEmailFetcher", m); } } // note: the same params get posted with every accountNum // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless. // we used to do only altemailaddrs, but now also include the name. updateUserInfo(request); String accountType = request.getParameter("accountType" + accountNum); if (Util.nullOrEmpty(accountType)) { result.put("status", 1); result.put("errorMessage", "No information for account #" + accountNum); return result; } String loginName = request.getParameter("loginName" + accountNum); String password = request.getParameter("password" + accountNum); String protocol = request.getParameter("protocol" + accountNum); // String port = request.getParameter("protocol" + accountNum); // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day String server = request.getParameter("server" + accountNum); String defaultFolder = request.getParameter("defaultFolder" + accountNum); if (server != null) server = server.trim(); if (loginName != null) loginName = loginName.trim(); // for these ESPs, the user may have typed in the whole address or just his/her login name if (accountType.equals("gmail") && loginName.indexOf("@") < 0) loginName = loginName + "@gmail.com"; if (accountType.equals("yahoo") && loginName.indexOf("@") < 0) loginName = loginName + "@yahoo.com"; if (accountType.equals("live") && loginName.indexOf("@") < 0) loginName = loginName + "@live.com"; if (accountType.equals("stanford") && loginName.indexOf("@") < 0) loginName = loginName + "@stanford.edu"; if (accountType.equals("gmail")) server = "imap.gmail.com"; // add imapdb stuff here. boolean imapDBLookupFailed = false; String errorMessage = ""; int errorStatus = 0; if (accountType.equals("email") && Util.nullOrEmpty(server)) { log.info("accountType = email"); defaultFolder = "Sent"; { // ISPDB from Mozilla imapDBLookupFailed = true; String emailDomain = loginName.substring(loginName.indexOf("@") + 1); log.info("Domain: " + emailDomain); // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html // to get around the need for installingthe unlimited strength encryption policy files. try { Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted"); field.setAccessible(true); field.set(null, java.lang.Boolean.FALSE); } catch (Exception ex) { ex.printStackTrace(); } // URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain); URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain); try { URLConnection urlConnection = url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(in); NodeList configList = doc.getElementsByTagName("incomingServer"); log.info("configList.getLength(): " + configList.getLength()); int i; for (i = 0; i < configList.getLength(); i++) { Node config = configList.item(i); NamedNodeMap attributes = config.getAttributes(); if (attributes.getNamedItem("type").getNodeValue().equals("imap")) { log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue()); Node param = config.getFirstChild(); String nodeName, nodeValue; String paramHostName = ""; String paramUserName = ""; do { if (param.getNodeType() == Node.ELEMENT_NODE) { nodeName = param.getNodeName(); nodeValue = param.getTextContent(); log.info(nodeName + "=" + nodeValue); if (nodeName.equals("hostname")) { paramHostName = nodeValue; } else if (nodeName.equals("username")) { paramUserName = nodeValue; } } param = param.getNextSibling(); } while (param != null); log.info("paramHostName = " + paramHostName); log.info("paramUserName = " + paramUserName); server = paramHostName; imapDBLookupFailed = false; if (paramUserName.equals("%EMAILADDRESS%")) { // Nothing to do with loginName } else if (paramUserName.equals("%EMAILLOCALPART%") || paramUserName.equals("%USERNAME%")) { // Cut only local part loginName = loginName.substring(0, loginName.indexOf('@') - 1); } else { imapDBLookupFailed = true; errorMessage = "Invalid auto configuration"; } break; // break after find first IMAP host name } } } catch (Exception e) { Util.print_exception("Exception trying to read ISPDB", e, log); errorStatus = 2; // status code = 2 => ispdb lookup failed errorMessage = "No automatic configuration available for " + emailDomain + ", please use the option to provide a private (IMAP) server. \nDetails: " + e.getMessage() + ". \nRunning with java -Djavax.net.debug=all may provide more details."; } } } if (imapDBLookupFailed) { log.info("ISPDB Fail"); result.put("status", errorStatus); result.put("errorMessage", errorMessage); // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user return result; } boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email") || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford") || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop") || accountType.startsWith("Thunderbird"); if (isServerAccount) { boolean sentOnly = "on".equals(request.getParameter("sent-messages-only")); return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly); } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) { try { String mboxDir = request.getParameter("mboxDir" + accountNum); String emailSource = request.getParameter("emailSource" + accountNum); // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb"); log.info("adding mbox account: " + mboxDir); errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders")); if (!Util.nullOrEmpty(errorMessage)) { result.put("errorMessage", errorMessage); result.put("status", 1); } else result.put("status", 0); } catch (MboxFolderNotReadableException e) { result.put("errorMessage", e.getMessage()); result.put("status", 1); } } else { result.put("errorMessage", "Sorry, unknown account type: " + accountType); result.put("status", 1); } return result; }