List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:SendMail.java
public static void main(String[] args) { try {/*from w ww.ja v a2 s. c o m*/ // 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:Main.java
public static void main(String args[]) throws Exception { String sessionCookie = null;/*from w w w .j a v a 2s . co m*/ URL url = new java.net.URL("http://127.0.0.1/yourServlet"); URLConnection con = url.openConnection(); if (sessionCookie != null) { con.setRequestProperty("cookie", sessionCookie); } con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteOut); out.flush(); byte buf[] = byteOut.toByteArray(); con.setRequestProperty("Content-type", "application/octet-stream"); con.setRequestProperty("Content-length", "" + buf.length); DataOutputStream dataOut = new DataOutputStream(con.getOutputStream()); dataOut.write(buf); dataOut.flush(); dataOut.close(); DataInputStream in = new DataInputStream(con.getInputStream()); int count = in.readInt(); in.close(); if (sessionCookie == null) { String cookie = con.getHeaderField("set-cookie"); if (cookie != null) { sessionCookie = parseCookie(cookie); System.out.println("Setting session ID=" + sessionCookie); } } System.out.println(count); }
From source file:com.adobe.aem.demo.Analytics.java
public static void main(String[] args) { String hostname = null;//from w ww. j a v a 2 s . 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: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);//from w w w . j av a 2s .c o 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:Main.java
public static String getURLContent(String urlStr) throws Exception { URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.setDoOutput(true);/*from w w w . ja va2 s. c om*/ connection.connect(); OutputStream ous = connection.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ous)); bw.write("index.htm"); bw.flush(); bw.close(); printRequestHeaders(connection); InputStream ins = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(ins)); StringBuffer sb = new StringBuffer(); String msg = null; while ((msg = br.readLine()) != null) { sb.append(msg); sb.append("\n"); // Append a new line } br.close(); return sb.toString(); }
From source file:org.anyframe.oden.bundle.auth.AuthTest.java
private static String sendRequest(String url, String msg) throws ShellException, Exception { PrintWriter writer = null;/* ww w . jav a2 s. com*/ String result = null; try { URLConnection conn = init(url); // send writer = new PrintWriter(conn.getOutputStream()); writer.println(msg); writer.flush(); // receive result = handleResult(conn); } finally { if (writer != null) { writer.close(); } } return result; }
From source file:PropertiesUtil.java
public static void store(Properties properties, URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("Url is not set."); } else {//from www . ja v a 2 s . co m URLConnection connection = url.openConnection(); connection.setDoOutput(true); store(properties, connection.getOutputStream()); return; } }
From source file:com.fluidops.iwb.cms.util.OpenUp.java
public static List<Statement> extract(String text, URI uri) throws IOException { List<Statement> res = new ArrayList<Statement>(); String textEncoded = URLEncoder.encode(text, "UTF-8"); String send = "format=rdfxml&text=" + textEncoded; // service limit is 10000 chars if (mode() == Mode.demo) send = stripToDemoLimit(send);//from w w w . ja v a 2 s . c o m // GET only works for smaller texts // URL url = new URL("http://openup.tso.co.uk/des/enriched-text?text=" + textEncoded + "&format=rdfxml"); URL url = new URL(getConfig().getOpenUpUrl()); URLConnection conn = url.openConnection(); conn.setDoOutput(true); IOUtils.write(send, conn.getOutputStream()); Repository repository = new SailRepository(new MemoryStore()); try { repository.initialize(); RepositoryConnection con = repository.getConnection(); con.add(conn.getInputStream(), uri.stringValue(), RDFFormat.RDFXML); RepositoryResult<Statement> iter = con.getStatements(null, null, null, false); while (iter.hasNext()) { Statement s = iter.next(); res.add(s); } } catch (Exception e) { throw new RuntimeException(e); } return res; }
From source file:org.exist.validation.TestTools.java
/** * * @param file File to be uploaded/*from w ww . j av a 2 s . co m*/ * @param target Target URL (e.g. xmldb:exist:///db/collection/document.xml) * @throws java.lang.Exception Oops..... */ public static void insertDocumentToURL(String file, String target) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(file); final URL url = new URL(target); final URLConnection connection = url.openConnection(); os = connection.getOutputStream(); TestTools.copyStream(is, os); } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } }
From source file:controlador.Red.java
/** * Envio de un fichero desde el Cliente Local al Server FTP. * @param rutaLocal Ruta del Cliente donde se buscara el fichero. * @param name Nombre con el cual se buscara y creara el fichero. * @return Estado de la operacion./* ww w.j a v a 2 s. c om*/ */ public static boolean sendFile(String rutaLocal, String name) { try { url = new URL(conexion + name); URLConnection urlConn = url.openConnection(); OutputStream os = urlConn.getOutputStream(); FileInputStream fis = new FileInputStream(new File(rutaLocal + name)); byte[] buffer = new byte[BUFFER_LENGTH]; int count; while ((count = fis.read(buffer)) > 0) { os.write(buffer, 0, count); } os.flush(); os.close(); fis.close(); return true; } catch (IOException ex) { ex.printStackTrace(); System.out.println("Problema al enviar un fichero al server: " + ex.getLocalizedMessage()); } return false; }