List of usage examples for java.net URL URL
public URL(String spec) throws MalformedURLException
From source file:Fetch5.java
public static void main(String args[]) throws Exception { String urlString = "java.sun.com"; CookieHandler.setDefault(new ListCookieHandler()); URL url = new URL(urlString); URLConnection connection = url.openConnection(); Object obj = connection.getContent(); url = new URL(urlString); connection = url.openConnection();/*from www . j av a2s. c o m*/ obj = connection.getContent(); }
From source file:SyncCustomObjects.java
public static void main(String[] args) { System.out.println("Executing Sync Custom Objects"); try {// www . ja va 2 s . co m URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL"); String marketoUserId = "CHANGE ME"; String marketoSecretKey = "CHANGE ME"; QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService"); MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName); MktowsPort port = service.getMktowsApiSoapPort(); // Create Signature DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); String text = df.format(new Date()); String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22); String encryptString = requestTimestamp + marketoUserId; SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] rawHmac = mac.doFinal(encryptString.getBytes()); char[] hexChars = Hex.encodeHex(rawHmac); String signature = new String(hexChars); // Set Authentication Header AuthenticationHeader header = new AuthenticationHeader(); header.setMktowsUserId(marketoUserId); header.setRequestTimestamp(requestTimestamp); header.setRequestSignature(signature); // Create Request ParamsSyncCustomObjects request = new ParamsSyncCustomObjects(); request.setObjTypeName("RoadShow"); JAXBElement<SyncOperationEnum> operation = new ObjectFactory() .createParamsSyncCustomObjectsOperation(SyncOperationEnum.UPSERT); request.setOperation(operation); ArrayOfCustomObj customObjects = new ArrayOfCustomObj(); CustomObj customObj = new CustomObj(); ArrayOfAttribute arrayOfKeyAttributes = new ArrayOfAttribute(); Attribute attr = new Attribute(); attr.setAttrName("MKTOID"); attr.setAttrValue("1090177"); Attribute attr2 = new Attribute(); attr2.setAttrName("rid"); attr2.setAttrValue("rid1"); arrayOfKeyAttributes.getAttributes().add(attr); arrayOfKeyAttributes.getAttributes().add(attr2); JAXBElement<ArrayOfAttribute> keyAttributes = new ObjectFactory() .createCustomObjCustomObjKeyList(arrayOfKeyAttributes); customObj.setCustomObjKeyList(keyAttributes); ArrayOfAttribute arrayOfValueAttributes = new ArrayOfAttribute(); Attribute city = new Attribute(); city.setAttrName("city"); city.setAttrValue("SanMateo"); Attribute zip = new Attribute(); zip.setAttrName("zip"); zip.setAttrValue("94404"); Attribute state = new Attribute(); state.setAttrName("state"); state.setAttrValue("California"); arrayOfValueAttributes.getAttributes().add(city); arrayOfValueAttributes.getAttributes().add(state); arrayOfValueAttributes.getAttributes().add(zip); JAXBElement<ArrayOfAttribute> valueAttributes = new ObjectFactory() .createCustomObjCustomObjAttributeList(arrayOfValueAttributes); customObj.setCustomObjAttributeList(valueAttributes); customObjects.getCustomObjs().add(customObj); SuccessSyncCustomObjects result = port.syncCustomObjects(request, header); JAXBContext context = JAXBContext.newInstance(SuccessSyncCustomObjects.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(result, System.out); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { URL url = new URL("http://www.java2s.com/style/download.png"); final BufferedImage trans = getTransparentImage(ImageIO.read(url), Color.BLACK); Runnable r = new Runnable() { @Override/*from w ww. j a v a 2 s . c om*/ public void run() { JLabel gui = new JLabel(new ImageIcon(trans)); JOptionPane.showMessageDialog(null, gui); } }; SwingUtilities.invokeLater(r); }
From source file:Main.java
public static void main(String[] argv) throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }/*from w ww . j a v a2s. co m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); URL url = new URL("https://hostname/index.html"); }
From source file:JSON.JasonJSON.java
public static void main(String[] args) throws Exception { URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json"); //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground //writes a perfectly formatted JSON file that is easy to read with Java. // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201"); try {/* w ww.jav a2s .c om*/ HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection(); // This part will read the data returned thru HTTP and load it into memory // I have this code left over from my CIT260 project. InputStream stream = urlCon.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // The next lines read certain parts of the JSON data and print it out on the screen //Creates the JSONObject object and loads the JSON file from the URLConnection //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something JSONObject json = new JSONObject(result.toString()); JSONObject coloradoInfo = (JSONObject) json.get("current_observation"); StringWriter out = new StringWriter(); json.write(out); String jsonTxt = json.toString(); System.out.print(jsonTxt); List<String> list = new ArrayList<>(); JSONArray array = json.getJSONArray(jsonTxt); System.out.print(jsonTxt); // for (int i =0;i<array.length();i++){ //list.add(array.getJSONObject(i).getString("current_observation")); //} String wunderGround = "Data downloaded from: " + coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: " + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: " + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: " + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: " + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: " + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: " + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: " + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string") + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: " + coloradoInfo.get("pressure_in"); System.out.println("\nColorado Springs Weather:"); System.out.println("____________________________________"); System.out.println(wunderGround); } catch (IOException e) { System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString() + "\nERROR: " + e.toString()); } }
From source file:ElementIteratorExample.java
public static void main(String args[]) throws Exception { if (args.length != 1) { System.err.println("Usage: java ElementIteratorExample input-URL"); }/*from w ww .java2 s .c o m*/ // Load HTML file synchronously URL url = new URL(args[0]); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); HTMLEditorKit htmlKit = new HTMLEditorKit(); HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument(); HTMLEditorKit.Parser parser = new ParserDelegator(); HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0); parser.parse(br, callback, true); // Parse ElementIterator iterator = new ElementIterator(htmlDoc); Element element; while ((element = iterator.next()) != null) { AttributeSet attributes = element.getAttributes(); Object name = attributes.getAttribute(StyleConstants.NameAttribute); if ((name instanceof HTML.Tag) && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) { // Build up content text as it may be within multiple elements StringBuffer text = new StringBuffer(); int count = element.getElementCount(); for (int i = 0; i < count; i++) { Element child = element.getElement(i); AttributeSet childAttributes = child.getAttributes(); if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) { int startOffset = child.getStartOffset(); int endOffset = child.getEndOffset(); int length = endOffset - startOffset; text.append(htmlDoc.getText(startOffset, length)); } } System.out.println(name + ": " + text.toString()); } } System.exit(0); }
From source file:SyncMultipleLeads.java
public static void main(String[] args) { System.out.println("Executing syncMultipleLeads"); try {//from w w w . ja v a2 s.com URL marketoSoapEndPoint = new URL("https://100-AEK-913.mktoapi.com/soap/mktows/2_1" + "?WSDL"); String marketoUserId = "demo17_1_809934544BFABAE58E5D27"; String marketoSecretKey = "27272727aa"; QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService"); MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName); MktowsPort port = service.getMktowsApiSoapPort(); // Create Signature DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); String text = df.format(new Date()); String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22); String encryptString = requestTimestamp + marketoUserId; SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] rawHmac = mac.doFinal(encryptString.getBytes()); char[] hexChars = Hex.encodeHex(rawHmac); String signature = new String(hexChars); // Set Authentication Header AuthenticationHeader header = new AuthenticationHeader(); header.setMktowsUserId(marketoUserId); header.setRequestTimestamp(requestTimestamp); header.setRequestSignature(signature); // Create Request ParamsSyncMultipleLeads request = new ParamsSyncMultipleLeads(); ObjectFactory objectFactory = new ObjectFactory(); JAXBElement<Boolean> dedup = objectFactory.createParamsSyncMultipleLeadsDedupEnabled(true); request.setDedupEnabled(dedup); ArrayOfLeadRecord arrayOfLeadRecords = new ArrayOfLeadRecord(); // Create First Lead Record LeadRecord rec1 = new LeadRecord(); JAXBElement<String> email = objectFactory.createLeadRecordEmail("t@t.com"); rec1.setEmail(email); Attribute attr1 = new Attribute(); attr1.setAttrName("FirstName"); attr1.setAttrValue("George"); Attribute attr2 = new Attribute(); attr2.setAttrName("LastName"); attr2.setAttrValue("of the Jungle"); ArrayOfAttribute aoa = new ArrayOfAttribute(); aoa.getAttributes().add(attr1); aoa.getAttributes().add(attr2); QName qname = new QName("http://www.marketo.com/mktows/", "leadAttributeList"); JAXBElement<ArrayOfAttribute> attrList = new JAXBElement(qname, ArrayOfAttribute.class, aoa); rec1.setLeadAttributeList(attrList); arrayOfLeadRecords.getLeadRecords().add(rec1); // Create Second Lead Record LeadRecord rec2 = new LeadRecord(); JAXBElement<String> email2 = objectFactory.createLeadRecordEmail("myemail@test.com"); rec2.setEmail(email2); Attribute attr11 = new Attribute(); attr11.setAttrName("FirstName"); attr11.setAttrValue("Nancy"); Attribute attr21 = new Attribute(); attr21.setAttrName("LastName"); attr21.setAttrValue("Lady"); ArrayOfAttribute aoa2 = new ArrayOfAttribute(); aoa2.getAttributes().add(attr11); aoa2.getAttributes().add(attr21); qname = new QName("http://www.marketo.com/mktows/", "leadAttributeList"); JAXBElement<ArrayOfAttribute> attrList2 = new JAXBElement(qname, ArrayOfAttribute.class, aoa2); rec2.setLeadAttributeList(attrList); arrayOfLeadRecords.getLeadRecords().add(rec2); request.setLeadRecordList(arrayOfLeadRecords); SuccessSyncMultipleLeads result = port.syncMultipleLeads(request, header); JAXBContext context = JAXBContext.newInstance(SuccessSyncMultipleLeads.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(result, System.out); } catch (Exception e) { e.printStackTrace(); } }
From source file:WebClient.java
public static void main(String[] args) throws Exception { CookieStore store = new MyCookieStore(); CookiePolicy policy = new MyCookiePolicy(); CookieManager handler = new CookieManager(store, policy); CookieHandler.setDefault(handler); URL url = new URL("http://localhost:8080/cookieTest.jsp"); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String input;/*w ww. j a va2 s . c o m*/ while ((input = reader.readLine()) != null) { System.out.println(input); } reader.close(); }
From source file:goeurotest.GoEuroTest.java
/** * @param args the command line arguments *//* ww w.ja v a2s . c o m*/ public static void main(String[] args) { Console console = System.console(); if (args.length != 1) { if (console != null) console.writer().println("Usage: java -jar GoEuroTest.jar <CITY_NAME>"); return; } URL url; try { url = new URL("http://api.goeuro.com/api/v2/position/suggest/en/" + args[0]); } catch (MalformedURLException ex) { if (console != null) console.writer().println("Malformed URL. Make sure the first parameter is the name of the city."); return; } String json; try { json = IOUtils.toString(url); } catch (IOException ex) { if (console != null) console.writer().println("Unable to contact the GoEuro API"); return; } JsonParser parser = new JsonParser(); try { JsonArray cities = parser.parse(json).getAsJsonArray(); if (cities.size() == 0) { if (console != null) console.writer().println("No results found"); return; } for (int i = 0; i < cities.size(); i++) { JsonObject city = cities.get(i).getAsJsonObject(); String id = city.get("_id").getAsString(); String name = city.get("name").getAsString(); String type = city.get("type").getAsString(); JsonObject geo_position = city.get("geo_position").getAsJsonObject(); String latitude = geo_position.get("latitude").getAsString(); String longitude = geo_position.get("longitude").getAsString(); String entry = id + "," + name + "," + type + "," + latitude + "," + longitude; System.out.println(entry); } } catch (Exception e) { if (console != null) console.writer().println("Malformed API response."); } }
From source file:GetLeadChanges.java
public static void main(String[] args) { System.out.println("Executing Get Lead Changes"); try {/*from w w w .ja v a 2 s .co m*/ URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL"); String marketoUserId = "CHANGE ME"; String marketoSecretKey = "CHANGE ME"; QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService"); MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName); MktowsPort port = service.getMktowsApiSoapPort(); // Create Signature DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); String text = df.format(new Date()); String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22); String encryptString = requestTimestamp + marketoUserId; SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] rawHmac = mac.doFinal(encryptString.getBytes()); char[] hexChars = Hex.encodeHex(rawHmac); String signature = new String(hexChars); // Set Authentication Header AuthenticationHeader header = new AuthenticationHeader(); header.setMktowsUserId(marketoUserId); header.setRequestTimestamp(requestTimestamp); header.setRequestSignature(signature); // Create Request ParamsGetLeadChanges request = new ParamsGetLeadChanges(); ObjectFactory objectFactory = new ObjectFactory(); JAXBElement<Integer> batchSize = objectFactory.createParamsGetLeadActivityBatchSize(10); request.setBatchSize(batchSize); ArrayOfString activities = new ArrayOfString(); activities.getStringItems().add("Visit Webpage"); activities.getStringItems().add("Click Link"); JAXBElement<ArrayOfString> activityFilter = objectFactory .createParamsGetLeadChangesActivityNameFilter(activities); request.setActivityNameFilter(activityFilter); // Create oldestCreateAt timestamp from 5 days ago GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(new Date().getTime()); gc.add(GregorianCalendar.DAY_OF_YEAR, -5); DatatypeFactory factory = DatatypeFactory.newInstance(); JAXBElement<XMLGregorianCalendar> oldestCreateAtValue = objectFactory .createStreamPositionOldestCreatedAt(factory.newXMLGregorianCalendar(gc)); StreamPosition sp = new StreamPosition(); sp.setOldestCreatedAt(oldestCreateAtValue); request.setStartPosition(sp); SuccessGetLeadChanges result = port.getLeadChanges(request, header); JAXBContext context = JAXBContext.newInstance(SuccessGetLeadChanges.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(result, System.out); } catch (Exception e) { e.printStackTrace(); } }