List of usage examples for java.net URLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.adobe.aem.demo.Analytics.java
public static void main(String[] args) { String hostname = null;//from w w w . jav a 2s. c o m String url = null; String eventfile = null; // Command line options for this tool Options options = new Options(); options.addOption("h", true, "Hostname"); options.addOption("u", true, "Url"); options.addOption("f", true, "Event data file"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("u")) { url = cmd.getOptionValue("u"); } if (cmd.hasOption("f")) { eventfile = cmd.getOptionValue("f"); } if (cmd.hasOption("h")) { hostname = cmd.getOptionValue("h"); } if (eventfile == null || hostname == null || url == null) { System.out.println("Command line parameters: -h hostname -u url -f path_to_XML_file"); System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } URLConnection urlConn = null; DataOutputStream printout = null; BufferedReader input = null; String u = "http://" + hostname + "/" + url; String tmp = null; try { URL myurl = new URL(u); urlConn = myurl.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String xml = readFile(eventfile, StandardCharsets.UTF_8); printout.writeBytes(xml); printout.flush(); printout.close(); input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); logger.debug(xml); while (null != ((tmp = input.readLine()))) { logger.debug(tmp); } printout.close(); input.close(); } catch (Exception ex) { logger.error(ex.getMessage()); } }
From source file:Main.java
public static void main(String args[]) throws Exception { int c;/*from ww w. j a v a 2 s. c om*/ URL hp = new URL("http://www.internic.net"); URLConnection hpCon = hp.openConnection(); long d = hpCon.getDate(); if (d == 0) System.out.println("No date information."); else System.out.println("Date: " + new Date(d)); System.out.println("Content-Type: " + hpCon.getContentType()); d = hpCon.getExpiration(); if (d == 0) System.out.println("No expiration information."); else System.out.println("Expires: " + new Date(d)); d = hpCon.getLastModified(); if (d == 0) System.out.println("No last-modified information."); else System.out.println("Last-Modified: " + new Date(d)); int len = hpCon.getContentLength(); if (len == -1) System.out.println("Content length unavailable."); else System.out.println("Content-Length: " + len); if (len != 0) { InputStream input = hpCon.getInputStream(); int i = len; while (((c = input.read()) != -1)) { // && (--i > 0)) { System.out.print((char) c); } input.close(); } else { System.out.println("No content available."); } }
From source file:com.maverick.ssl.SSLSocket.java
public static void main(String[] args) { try {/* w ww.j a va2s .c o m*/ HttpsURLStreamHandlerFactory.addHTTPSSupport(); URL url = new URL("https://localhost"); //$NON-NLS-1$ URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(false); con.setAllowUserInteraction(false); con.setRequestProperty("Accept", //$NON-NLS-1$ "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*"); //$NON-NLS-1$ con.setRequestProperty("Accept-Encoding", "gzip, deflate"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("Accept-Language", "en-gb"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("User-Agent", //$NON-NLS-1$ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"); //$NON-NLS-1$ con.connect(); InputStream in = con.getInputStream(); int read; while ((read = in.read()) > -1) { System.out.write(read); } } catch (SSLIOException ex) { ex.getRealException().printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.zuora.api.UsageAdjInvoiceRegenerator.java
public static void main(String[] args) { String exportIdPRPC, exportIdII, exportFileIdII, exportFileIdPRPC, queryII, queryPRPC; boolean hasArgs = false; if (args != null && args.length >= 1) { UsageAdjInvoiceRegenerator.PROPERTY_FILE_NAME = args[0]; hasArgs = true;//from w w w.j a va 2s.co m } AppParamManager.initParameters(hasArgs); if (!AppParamManager.TASK_ID.equals("")) { try { zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME, AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION); zApiClient.login(); } catch (Exception ex) { Logger.print(ex); Logger.print("RefreshSession - There's exception in the API call."); } queryPRPC = AppParamManager.PRPCexportQuery; queryII = AppParamManager.IIexportQuery; exportIdPRPC = zApiClient.createExport(queryPRPC); exportIdII = zApiClient.createExport(queryII); // ERROR createExport fails if (exportIdII == null || exportIdII.equals("")) { Logger.print("Error. Failed to create Invoice Item Export"); //return false; } // ERROR createExport fails if (exportIdPRPC == null || exportIdPRPC.equals("")) { Logger.print("Error. Failed to create PRPC export"); //return false; } exportFileIdII = zApiClient.getExportFileId(exportIdII); if (exportFileIdII == null) { Logger.print("Error. Failed to get Invoice Item Export file Id"); //log.closeLogFile(); //return false; } exportFileIdPRPC = zApiClient.getExportFileId(exportIdPRPC); if (exportFileIdPRPC == null) { Logger.print("Error. Failed to get PRPC Export file Id"); //log.closeLogFile(); //return false; } // get the export file from zuora //zApiClient.getFile(exportFileIdII, exportFileIdTI); /* Logger.print("II export ID: "+exportFileIdII); Logger.print("TI export ID: "+exportFileIdTI); */ Logger.print("Opening Export file"); //Base64 bs64 = new BASE64Encoder(); /* String login = AppParamManager.USER_NAME+":"+AppParamManager.USER_PASSWORD; String authorization ="Basic "+ Base64.encodeBase64String(login.getBytes()); String zendpoint = ""; */ String authorization = ""; //Base64 bs64 = new BASE64Encoder(); if (AppParamManager.USER_SESSION.isEmpty()) { String login = AppParamManager.USER_NAME + ":" + AppParamManager.USER_PASSWORD; authorization = "Basic " + Base64.encodeBase64String(login.getBytes()); } else { authorization = "ZSession " + AppParamManager.USER_SESSION; } String zendpoint = ""; try { /* if( AppParamManager.API_URL.contains("api") ){ //look in api sandbox zendpoint = "https://apisandbox.zuora.com/apps/api/file/"; } else { //look in production zendpoint = "https://www.zuora.com/apps/api/file/"; } */ int index = AppParamManager.API_URL.indexOf("apps"); index = index + 5; zendpoint = AppParamManager.API_URL.substring(0, index) + "api/file/"; Logger.print(zendpoint); //zendpoint = AppParamManager.FILE_URL; //Start reading Invoice Items String zendpointII = zendpoint + exportFileIdII + "/"; URL url = new URL(zendpointII); URLConnection uc = url.openConnection(); //Logger.print("Opening invoice item file: "+exportFileIdII+" authorization: "+authorization); uc.setRequestProperty("Authorization", authorization); InputStream content = (InputStream) uc.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); CSVReader cvsReader = new CSVReader(in); List<String[]> batchOfRawDataList = null; while ((batchOfRawDataList = cvsReader.parseEntity()) != null) { UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(), "InvoiceItem"); } in.close(); String zenpointPRPC = zendpoint + exportFileIdPRPC + "/"; url = new URL(zenpointPRPC); uc = url.openConnection(); uc.setRequestProperty("Authorization", authorization); content = (InputStream) uc.getInputStream(); in = new BufferedReader(new InputStreamReader(content)); cvsReader = new CSVReader(in); while ((batchOfRawDataList = cvsReader.parseEntity()) != null) { UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(), "PRPCItem"); } in.close(); Logger.print("start processing values"); UsageAdjInvoiceRegenerator chargeAdjustment = new UsageAdjInvoiceRegenerator(); int[] results; int totalErrors = 0; String emailmsg = ""; Logger.print("----------------------------------------"); Logger.print("start creating usages"); results = zApiClient.createUsageItems(newUsageCollection); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage creation "; } totalErrors = totalErrors + results[1]; Logger.print("start cancelling invoices"); results = zApiClient.alterInvoices(newUsageCollection, "cancel"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice cancellation "; } totalErrors = totalErrors + results[1]; Logger.print("start deleting usages"); results = zApiClient.deleteUsageItems(deleteList); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage deletion "; } totalErrors = totalErrors + results[1]; Logger.print("start regenerating invoices"); results = zApiClient.alterInvoices(newUsageCollection, "generate"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice generation "; } totalErrors = totalErrors + results[1]; Logger.print("start deleting old invoices"); results = zApiClient.alterInvoices(newUsageCollection, "delete"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice deletion "; } totalErrors = totalErrors + results[1]; // Create the attachment EmailAttachment attachment = new EmailAttachment(); if (totalErrors > 0) { String logFileName = AppParamManager.OUTPUT_FOLDER_LOCATION + File.separator + "runtime_log_" + AppParamManager.OUTPUT_FILE_POSTFIX + ".txt"; attachment.setPath(logFileName); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("System Log"); attachment.setName("System Log"); } MultiPartEmail email = new MultiPartEmail(); email.setSmtpPort(587); email.setAuthenticator( new DefaultAuthenticator(AppParamManager.EMAIL_ADDRESS, AppParamManager.EMAIL_PASSWORD)); email.setDebug(false); email.setHostName("smtp.gmail.com"); email.setFrom("zuora@gmail.com"); if (totalErrors > 0) { email.setSubject("Base Calc Processor Finished with Errors"); email.setMsg("The base calc processing has finished " + emailmsg + "records successfully."); } else { email.setSubject("Base Calc Processor Finished Successfully"); emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice "; email.setMsg("The base calc processing has finished " + emailmsg + "records successfully."); } email.setTLS(true); email.addTo(AppParamManager.RECIPIENT_ADDRESS); if (totalErrors > 0) { email.attach(attachment); } email.send(); System.out.println("Mail sent!"); if (hasArgs) { Connection conn = AppParamManager.getConnection(); Statement stmt = conn.createStatement(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); java.util.Date date = new Date(); stmt.executeUpdate("UPDATE TASK SET STATUS = 'completed', END_TIME = '" + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID); Utility.saveLogToDB(conn); conn.close(); } } catch (Exception e) { Logger.print("Failure, gettingFile."); Logger.print("Error getting the export file: " + e.getMessage()); //System.out.println("Error getting the export file: "+e.getMessage()); try { Connection conn = AppParamManager.getConnection(); Statement stmt = conn.createStatement(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); java.util.Date date = new Date(); stmt.executeUpdate("UPDATE TASK SET STATUS = 'failed', END_TIME = '" + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID); Utility.saveLogToDB(conn); conn.close(); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } } else { Logger.print("No tasks in wait status"); } }
From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authpost <username> <password> <filepath> <url>"); System.exit(-1);/* w w w . j a v a 2 s .co m*/ } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; URL url = new URL(args[3]); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); conn.setRequestProperty("name", upload.getName()); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; conn.setRequestProperty("Content-type", contentType); BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload)); BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = filein.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } filein.close(); out.close(); String s = null; BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((s = in.readLine()) != null) { System.out.println(s); } }
From source file:URLConnectionTest.java
public static void main(String[] args) { try {/*w w w .ja va 2 s. c om*/ String urlName; if (args.length > 0) urlName = args[0]; else urlName = "http://java.sun.com"; URL url = new URL(urlName); URLConnection connection = url.openConnection(); // set username, password if specified on command line if (args.length > 2) { String username = args[1]; String password = args[2]; String input = username + ":" + password; String encoding = base64Encode(input); connection.setRequestProperty("Authorization", "Basic " + encoding); } connection.connect(); // print header fields Map<String, List<String>> headers = connection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) System.out.println(key + ": " + value); } // print convenience functions System.out.println("----------"); System.out.println("getContentType: " + connection.getContentType()); System.out.println("getContentLength: " + connection.getContentLength()); System.out.println("getContentEncoding: " + connection.getContentEncoding()); System.out.println("getDate: " + connection.getDate()); System.out.println("getExpiration: " + connection.getExpiration()); System.out.println("getLastModifed: " + connection.getLastModified()); System.out.println("----------"); Scanner in = new Scanner(connection.getInputStream()); // print first ten lines of contents for (int n = 1; in.hasNextLine() && n <= 10; n++) System.out.println(in.nextLine()); if (in.hasNextLine()) System.out.println(". . ."); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
private static InputStream retrieve(String url) throws IOException { URL target = new URL(url); URLConnection connection = target.openConnection(); return connection.getInputStream(); }
From source file:Main.java
public static Drawable GetUrlDrawable(String url) { try {//from w w w . ja v a2s.co m URL aryURI = new URL(url); URLConnection conn = aryURI.openConnection(); InputStream is = conn.getInputStream(); Bitmap bmp = BitmapFactory.decodeStream(is); return new BitmapDrawable(bmp); } catch (Exception e) { Log.e("ERROR", "urlImage2Drawable failed with image url at " + url, e); return null; } }
From source file:Main.java
public static Bitmap getBitmap(String biturl) { Bitmap bitmap = null;//from w w w . j a v a 2 s. co m try { URL url = new URL(biturl); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(new BufferedInputStream(in)); } catch (Exception e) { e.printStackTrace(); } return bitmap; }
From source file:com.digitallizard.bbcnewsreader.resource.web.ImageDownloader.java
public static byte[] getImage(URL url) throws Exception { URLConnection connection = url.openConnection(); InputStream stream = connection.getInputStream(); BufferedInputStream inputbuffer = new BufferedInputStream(stream, 8000); ByteArrayBuffer arraybuffer = new ByteArrayBuffer(50); int current = 0; while ((current = inputbuffer.read()) != -1) { arraybuffer.append((byte) current); }/* w w w. j av a2s . c om*/ byte[] image = arraybuffer.toByteArray(); return image; }