List of usage examples for java.net URL URL
public URL(String spec) throws MalformedURLException
From source file:URLConnectionTest.java
public static void main(String[] args) { try {//from www .j a v a 2 s.c o m 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:Naive.java
public static void main(String[] args) throws Exception { // Basic access authentication setup String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; // CHANGEME: the API version to use String practiceid = "000000"; // CHANGEME: the practice ID to use // Find the authentication path Map<String, String> auth_prefix = new HashMap<String, String>(); auth_prefix.put("v1", "oauth"); auth_prefix.put("preview1", "oauthpreview"); auth_prefix.put("openpreview1", "oauthopenpreview"); URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token"); HttpURLConnection conn = (HttpURLConnection) authurl.openConnection(); conn.setRequestMethod("POST"); // Set the Authorization request header String auth = Base64.encodeBase64String((key + ':' + secret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + auth); // Since this is a POST, the parameters go in the body conn.setDoOutput(true);//ww w . j a v a2 s. co m String contents = "grant_type=client_credentials"; DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); // Read the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); // Decode from JSON and save the token for later String response = sb.toString(); JSONObject authorization = new JSONObject(response); String token = authorization.get("access_token").toString(); // GET /departments HashMap<String, String> params = new HashMap<String, String>(); params.put("limit", "1"); // Set up the URL, method, and Authorization header URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?" + urlencode(params)); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Bearer " + token); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject departments = new JSONObject(response); System.out.println(departments.toString()); // POST /appointments/{appointmentid}/notes params = new HashMap<String, String>(); params.put("notetext", "Hello from Java!"); url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + token); // POST parameters go in the body conn.setDoOutput(true); contents = urlencode(params); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject note = new JSONObject(response); System.out.println(note.toString()); }
From source file:MainGeneratePicasaIniFile.java
public static void main(String[] args) { try {/*from w w w .j a v a 2 s . co m*/ Calendar start = Calendar.getInstance(); start.set(1899, 11, 30, 0, 0); PicasawebService myService = new PicasawebService("My Application"); myService.setUserCredentials(args[0], args[1]); // Get a list of all entries URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album"); System.out.println("Getting Picasa Web Albums entries...\n"); UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class); // resultFeed. File root = new File(args[2]); File[] albuns = root.listFiles(); int j = 0; List<GphotoEntry> entries = resultFeed.getEntries(); for (int i = 0; i < entries.size(); i++) { GphotoEntry entry = entries.get(i); String href = entry.getHtmlLink().getHref(); String name = entry.getTitle().getPlainText(); for (File album : albuns) { if (album.getName().equals(name) && !href.contains("02?")) { File picasaini = new File(album, "Picasa.ini"); if (!picasaini.exists()) { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("[Picasa]\n"); builder.append("name="); builder.append(name); builder.append("\n"); builder.append("location="); Collection<Extension> extensions = entry.getExtensions(); for (Extension extension : extensions) { if (extension instanceof GphotoLocation) { GphotoLocation location = (GphotoLocation) extension; if (location.getValue() != null) { builder.append(location.getValue()); } } } builder.append("\n"); builder.append("category=Folders on Disk"); builder.append("\n"); builder.append("date="); String source = name.substring(0, 10); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); Date date = formater.parse(source); Calendar end = Calendar.getInstance(); end.setTime(date); builder.append(daysBetween(start, end)); builder.append(".000000"); builder.append("\n"); builder.append(args[0]); builder.append("_lh="); builder.append(entry.getGphotoId()); builder.append("\n"); builder.append("P2category=Folders on Disk"); builder.append("\n"); URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0] + "/albumid/" + entry.getGphotoId()); AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class); for (GphotoEntry photo : feed.getEntries()) { builder.append("\n"); builder.append("["); builder.append(photo.getTitle().getPlainText()); builder.append("]"); builder.append("\n"); long id = Long.parseLong(photo.getGphotoId()); builder.append("IIDLIST_"); builder.append(args[0]); builder.append("_lh="); builder.append(Long.toHexString(id)); builder.append("\n"); } System.out.println(builder.toString()); IOUtils.write(builder.toString(), new FileOutputStream(picasaini)); j++; } } } } System.out.println(j); System.out.println("\nTotal Entries: " + entries.size()); } catch (Exception e) { e.printStackTrace(); } }
From source file:DownloadFileFromURL.java
public static void main(String[] args) throws Exception { urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/pg11.TXT"); urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/lorem.TXT"); urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/pg1661.TXT"); urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/cacerts"); urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/eula.rtf"); urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/Story.JPG"); urlList.add("http://downloads.solarwinds.com/solarwinds/Release/Management/solarwinds.png"); for (int iUrl = 0; iUrl < urlList.size(); iUrl++) { try {//from www . j a v a 2 s .co m String urlString = urlList.get(iUrl); //All File Locations go here url = new URL(urlString); } catch (MalformedURLException ex) { Logger.getLogger(DownloadFileFromURL.class.getName()).log(Level.SEVERE, null, ex); } try { // open all the url connections here. con = url.openConnection(); } catch (IOException ex) { Logger.getLogger(DownloadFileFromURL.class.getName()).log(Level.SEVERE, null, ex); } dis = new DataInputStream(con.getInputStream()); fileData = new byte[con.getContentLength()]; for (int q = 0; q < fileData.length; q++) { fileData[q] = dis.readByte(); } dis.close(); // close the data input stream String fName = FilenameUtils.getName(url.getPath()); fos = new FileOutputStream(new File(fName)); //FILE Save Location goes here fos.write(fileData); // write out the file we want to save. fos.close(); // close the output stream writer } // end of for }
From source file:demo.wssec.client.Client.java
public static void main(String args[]) throws Exception { if (args.length == 0) { System.out.println("please specify wsdl"); System.exit(1);/* w w w .ja v a 2s . c o m*/ } URL wsdlURL; File wsdlFile = new File(args[0]); if (wsdlFile.exists()) { wsdlURL = wsdlFile.toURI().toURL(); } else { wsdlURL = new URL(args[0]); } SpringBusFactory bf = new SpringBusFactory(); URL busFile = new ClassPathResource("wssec-client.xml").getURL(); Bus bus = bf.createBus(busFile.toString()); SpringBusFactory.setDefaultBus(bus); SpringBusFactory.setThreadDefaultBus(bus); Service service = Service.create(wsdlURL, SERVICE_NAME); Greeter port = service.getPort(PORT_NAME, Greeter.class); System.out.println("Invoking greetMe..."); try { String resp = port.greetMe(System.getProperty("user.name")); System.out.println("Server responded with: " + resp); System.out.println(); } catch (Exception e) { System.out.println("Invocation failed with the following: " + e.getCause()); System.out.println(); } System.exit(0); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { URL url1 = new URL("http://localhost:8080/audio/1.au"); URL url2 = new URL("http://localhost:8080/audio/2.au"); MainClass sac1 = new MainClass(url1); MainClass sac2 = new MainClass(url2); MainClass sac3 = new MainClass("1.au"); sac1.play();/*from ww w.j a v a2 s . co m*/ sac2.loop(); sac3.play(); try { // Delay for loop Thread.sleep(2000); } catch (InterruptedException ie) { } sac2.stop(); }
From source file:SunAudioClip.java
public static void main(String args[]) throws Exception { URL url1 = new URL("http://localhost:8080/audio/1.au"); URL url2 = new URL("http://localhost:8080/audio/2.au"); SunAudioClip sac1 = new SunAudioClip(url1); SunAudioClip sac2 = new SunAudioClip(url2); SunAudioClip sac3 = new SunAudioClip("1.au"); sac1.play();//from w w w .j a v a 2s .c o m sac2.loop(); sac3.play(); try { // Delay for loop Thread.sleep(2000); } catch (InterruptedException ie) { } sac2.stop(); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); ServerSocket ss = ssf.createServerSocket(443); while (true) { Socket s = ss.accept();// w w w . ja v a 2s . c o m PrintStream out = new PrintStream(s.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String info = null; String request = null; String refer = null; while ((info = in.readLine()) != null) { if (info.startsWith("GET")) { request = info; } if (info.startsWith("Referer:")) { refer = info; } if (info.equals("")) break; } if (request != null) { out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html"); int sp1 = request.indexOf(' '); int sp2 = request.indexOf(' ', sp1 + 1); String filename = request.substring(sp1 + 2, sp2); if (refer != null) { sp1 = refer.indexOf(' '); refer = refer.substring(sp1 + 1, refer.length()); if (!refer.endsWith("/")) { refer = refer + "/"; } filename = refer + filename; } URL con = new URL(filename); InputStream gotoin = con.openStream(); int n = gotoin.available(); byte buf[] = new byte[1024]; out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html"); out.println("Content_Length:" + n + "\n"); while ((n = gotoin.read(buf)) >= 0) { out.write(buf, 0, n); } out.close(); s.close(); in.close(); } } }
From source file:GoogleImages.java
public static void main(String[] args) throws InterruptedException { String searchTerm = "s woman"; // term to search for (use spaces to separate terms) int offset = 40; // we can only 20 results at a time - use this to offset and get more! String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet) String source = null; // string to save raw HTML source code // format spaces in URL to avoid problems searchTerm = searchTerm.replaceAll(" ", "%20"); // get Google image search HTML source code; mostly built from PhyloWidget example: // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java int offset2 = 0; Set urlsss = new HashSet<String>(); while (offset2 < 600) { try {//from w ww .ja v a 2s.c o m URL query = new URL("https://www.google.ru/search?start=" + offset2 + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A"); HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection... urlc.setInstanceFollowRedirects(true); urlc.setRequestProperty("User-Agent", ""); urlc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file StringBuffer response = new StringBuffer(); char[] buffer = new char[1024]; while (true) { int charsRead = in.read(buffer); if (charsRead == -1) { break; } response.append(buffer, 0, charsRead); } in.close(); // close input stream (also closes network connection) source = response.toString(); } // any problems connecting? let us know catch (Exception e) { e.printStackTrace(); } // print full source code (for debugging) // println(source); // extract image URLs only, starting with 'imgurl' if (source != null) { // System.out.println(source); int c = StringUtils.countMatches(source, "http://www.vmir.su"); System.out.println(c); int index = source.indexOf("src="); System.out.println(source.subSequence(index, index + 200)); while (index >= 0) { System.out.println(index); index = source.indexOf("src=", index + 1); if (index == -1) { break; } String rr = source.substring(index, index + 200 > source.length() ? source.length() : index + 200); if (rr.contains("\"")) { rr = rr.substring(5, rr.indexOf("\"", 5)); } System.out.println(rr); urlsss.add(rr); } } offset2 += 20; Thread.sleep(1000); System.out.println("off set = " + offset2); } System.out.println(urlsss); urlsss.forEach(new Consumer<String>() { public void accept(String s) { try { saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg"); } catch (IOException ex) { Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex); } } }); // String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\""); // older regex, no longer working but left for posterity // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))"); // (?i) means case-insensitive // for (int i = 0; i < m.length; i++) { // iterate all results of the match // println(i + ":\t" + m[i][1]); // print (or store them)** // } }
From source file:Main.java
public static void main(String[] args) throws Exception { if (args[0].equals("-m")) streamMidiSequence(new URL(args[1])); else/*www .j av a2 s . co m*/ streamSampledAudio(new URL(args[0])); // Exit explicitly. // This is needed because the audio system starts background threads. System.exit(0); }