List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
From source file:SendMail.java
public static void main(String[] args) { try {/*from w w w . j a va2s . c om*/ // If the user specified a mailhost, tell the system about it. if (args.length >= 1) System.getProperties().put("mail.host", args[0]); // A Reader stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Ask the user for the from, to, and subject lines System.out.print("From: "); String from = in.readLine(); System.out.print("To: "); String to = in.readLine(); System.out.print("Subject: "); String subject = in.readLine(); // Establish a network connection for sending mail URL u = new URL("mailto:" + to); // Create a mailto: URL URLConnection c = u.openConnection(); // Create its URLConnection c.setDoInput(false); // Specify no input from it c.setDoOutput(true); // Specify we'll do output System.out.println("Connecting..."); // Tell the user System.out.flush(); // Tell them right now c.connect(); // Connect to mail host PrintWriter out = // Get output stream to host new PrintWriter(new OutputStreamWriter(c.getOutputStream())); // We're talking to the SMTP server now. // Write out mail headers. Don't let users fake the From address out.print("From: \"" + from + "\" <" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ">\r\n"); out.print("To: " + to + "\r\n"); out.print("Subject: " + subject + "\r\n"); out.print("\r\n"); // blank line to end the list of headers // Now ask the user to enter the body of the message System.out.println("Enter the message. " + "End with a '.' on a line by itself."); // Read message line by line and send it out. String line; for (;;) { line = in.readLine(); if ((line == null) || line.equals(".")) break; out.print(line + "\r\n"); } // Close (and flush) the stream to terminate the message out.close(); // Tell the user it was successfully sent. System.out.println("Message sent."); } catch (Exception e) { // Handle any exceptions, print error message. System.err.println(e); System.err.println("Usage: java SendMail [<mailhost>]"); } }
From source file:geocodingsql.Main.java
/** * @param args the command line arguments */// w w w. j a v a 2s . c om public static void main(String[] args) throws JSONException { Main x = new Main(); ResultSet rs = null; String string = ""; x.establishConnection(); rs = x.giveName(); try { while (rs.next()) { string += rs.getString(1) + " "; } JOptionPane.showMessageDialog(null, string, "authors", 1); } catch (Exception e) { System.out.println("Problem when printing the database."); } x.closeConnection(); // Now do Geocoding String req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=41.3166662867211,-72.9062497615814&result_type=point_of_interest&key=" + key; try { URL url = new URL(req + "&sensor=false"); URLConnection conn = url.openConnection(); ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copy(conn.getInputStream(), output); output.close(); req = output.toString(); } catch (Exception e) { System.out.println("Geocoding Error"); } JSONObject jObject = new JSONObject(req); JSONArray resultArray = jObject.getJSONArray("results"); //this prints out the neighborhood of the provided coordinates System.out.println(resultArray.getJSONObject(0).getJSONArray("address_components") .getJSONObject("neighborhood").getString("long_name")); }
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;/*from w w w .j a v a 2 s.c o m*/ while ((input = reader.readLine()) != null) { System.out.println(input); } reader.close(); }
From source file:org.craftercms.cstudio.publishing.StopServiceMain.java
public static void main(String[] args) throws Exception { FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( "classpath:spring/shutdown-context.xml"); ReadablePropertyPlaceholderConfigurer properties = (ReadablePropertyPlaceholderConfigurer) context .getBean("cstudioShutdownProperties"); if (properties != null) { String url = getProperty(properties, PROP_URL); String path = getProperty(properties, PROP_SERVICE_PATH); String port = getProperty(properties, PROP_PORT); String password = URLEncoder.encode(getProperty(properties, PROP_PASSWORD), "UTF-8"); String target = url + ":" + port + path; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending a stop request to " + target); }//w w w .j a v a 2s. c om target = target + "?" + StopServiceServlet.PARAM_PASSWORD + "=" + password; URL serviceUrl = new URL(target); HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(10000); connection.connect(); try { connection.getContent(); } catch (ConnectException e) { // ignore this error (server will terminate as soon as the request is sent out) } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error(PROPERTIES_NAME + " is not present in shutdown-context.xml"); } } context.close(); }
From source file:Base64Stuff.java
public static void main(String[] args) { //Random random = new Random(); try {//w w w . j a v a2 s . com File file1 = new File("C:\\\\Program Files\\\\ImageJ\\\\images\\\\confocal-series-10001.tif"); //File file2 = new File("C:\\Program Files\\ImageJ\\images\\confocal-series-10000.tif"); ImagePlus image1 = new ImagePlus( "C:\\\\Program Files\\\\ImageJ\\\\images\\\\confocal-series-10001.tif"); //ImagePlus image2 = new ImagePlus("C:\\Program Files\\ImageJ\\images\\two.tif"); byte[] myBytes1 = org.apache.commons.io.FileUtils.readFileToByteArray(file1); //byte[] myBytes2 = org.apache.commons.io.FileUtils.readFileToByteArray(file2); //random.nextBytes(randomBytes); //String internalVersion1 = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(myBytes1); //String internalVersion2 = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(myBytes2); byte[] apacheBytes1 = org.apache.commons.codec.binary.Base64.encodeBase64(myBytes1); //byte[] apacheBytes2 = org.apache.commons.codec.binary.Base64.encodeBase64(myBytes2); String string1 = new String(apacheBytes1); //String string2 = new String(apacheBytes2); System.out.println("File1 length:" + string1.length()); //System.out.println("File2 length:" + string2.length()); System.out.println(string1); //System.out.println(string2); System.out.println("Image1 size: (" + image1.getWidth() + "," + image1.getHeight() + ")"); //System.out.println("Image2 size: (" + image2.getWidth() + "," + image2.getHeight() + ")"); String urlParameters = "data=" + string1 + "&size=1000x1000"; URL url = new URL("http://api.qrserver.com/v1/create-qr-code/"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); //byte buf[] = new byte[700000000]; BufferedInputStream reader = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream("C:\\Users\\expertoweb\\Desktop\\qrcode2.png")); int data; while ((data = reader.read()) != -1) { bos.write(data); } writer.close(); reader.close(); bos.close(); } catch (IOException e) { } }
From source file:com.maverick.ssl.SSLSocket.java
public static void main(String[] args) { try {//ww w . ja v a2 s . com 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.adobe.aem.demo.Analytics.java
public static void main(String[] args) { String hostname = null;/*from w w w . j av a2 s . c om*/ 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:org.wso2.msf4j.example.SampleClient.java
public static void main(String[] args) throws IOException { HttpEntity messageEntity = createMessageForComplexForm(); // Uncomment the required message body based on the method that want to be used //HttpEntity messageEntity = createMessageForMultipleFiles(); //HttpEntity messageEntity = createMessageForSimpleFormStreaming(); String serverUrl = "http://localhost:8080/formService/complexForm"; // Uncomment the required service url based on the method that want to be used //String serverUrl = "http://localhost:8080/formService/multipleFiles"; //String serverUrl = "http://localhost:8080/formService/simpleFormStreaming"; URL url = URI.create(serverUrl).toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", messageEntity.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { messageEntity.writeTo(out);// w ww .ja va 2 s . c o m } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); System.out.println(response); }
From source file:org.wso2.charon3.samples.user.sample01.CreateUserSample.java
public static void main(String[] args) { try {// w w w. j a va 2s . com String url = "http://localhost:8080/scim/v2/Users"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Setting basic post request con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/scim+json"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(createRequestBody); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode == HttpURLConnection.HTTP_CREATED) { // success in = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //printing result from response System.out.println("Response Code : " + responseCode); System.out.println("Response Message : " + con.getResponseMessage()); System.out.println("Response Content : " + response.toString()); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:GcmSender.java
public static void main(String[] ar) { String message = "<Push message string here>"; String to = "<Device token here>"; try {/* ww w . j ava 2 s . c o m*/ // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); try { jData.put("message", message.trim()); // Where to send GCM message. if (to.length() != 0) { jGcmData.put("to", to.trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } }