List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.trendmicro.hdfs.webdav.tool.Get.java
public static void main(String[] args) throws Exception { // Process command line Options options = new Options(); options.addOption("d", "debug", false, "Enable debug logging"); CommandLine cmd = null;//from www.j a v a 2s . c om try { cmd = new PosixParser().parse(options, args); } catch (ParseException e) { printUsageAndExit(options, -1); } boolean debug = cmd.hasOption('d'); args = cmd.getArgs(); if (args.length < 1) { printUsageAndExit(options, -1); } // Do the fetch AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL url = new AuthenticatedURL(); HttpURLConnection conn = url.openConnection(new URL(args[0]), token); if (debug) { System.out.println("Token value: " + token); System.out.println("Status code: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } reader.close(); } System.out.println(); }
From source file:org.javaee7.ejb.stateless.remote.AccountSessionBeanWithInterface.java
public static void main(String[] args) { try {//www. j av a2 s . c o m ObjectMapper mapper = new ObjectMapper(); URL url = new URL("http://localhost:8180/account-1.0-SNAPSHOT/statistics"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; String result = null; while ((output = br.readLine()) != null) { result = result + output; } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
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);// w w w. ja v a2s .c o m connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", messageEntity.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { messageEntity.writeTo(out); } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); System.out.println(response); }
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 www . j a va 2 s. 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:net.securnetwork.itebooks.downloader.EbookDownloader.java
/** * Program main method./*from ww w .ja va 2s. com*/ * * @param args the program arguments */ public static void main(String[] args) { if (validateArguments(args)) { int start = MIN_EBOOK_INDEX; int end = getLastEbookIndex(); String destinationFolder = null; // Check if resume mode if (args.length == 1 && args[0].equals(RESUME_ARG)) { start = Integer.parseInt(prefs.get(LAST_SAVED_EBOOK_PREF, MIN_EBOOK_INDEX - 1 + "")) + 1; //$NON-NLS-1$ destinationFolder = prefs.get(OUTPUT_FOLDER_PREF, null); } else { destinationFolder = getDestinationFolder(args); } if (destinationFolder == null) { System.err.println(Messages.getString("EbookDownloader.NoDestinationFolderFound")); //$NON-NLS-1$ return; } else { // Possibly fix the destination folder path destinationFolder = destinationFolder.replace("\\", "/"); if (!destinationFolder.endsWith("/")) { destinationFolder += "/"; } prefs.put(OUTPUT_FOLDER_PREF, destinationFolder); } if (args.length == 3) { start = getStartIndex(args); end = getEndIndex(args); } try { for (int i = start; i <= end; i++) { String ebookPage = BASE_EBOOK_URL + i + SLASH; Source sourceHTML = new Source(new URL(ebookPage)); List<Element> allTables = sourceHTML.getAllElements(HTMLElementName.TABLE); Element detailsTable = allTables.get(0); // Try to build an info bean for the ebook String bookTitle = EbookPageParseUtils.getTitle(detailsTable); if (bookTitle != null) { EbookInfo ebook = createEbookInfo(bookTitle, i, detailsTable); String filename = destinationFolder + Misc.getValidFilename(ebook.getTitle(), ebook.getSubTitle(), ebook.getYear(), ebook.getFileFormat()); System.out.print(MessageFormat.format(Messages.getString("EbookDownloader.InfoDownloading"), //$NON-NLS-1$ new Object[] { ebook.getSiteId() })); try { URL ebookPageURL = new URL(ebook.getDownloadLink()); HttpURLConnection con = (HttpURLConnection) ebookPageURL.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Referer", ebookPage); InputStream conIS = con.getInputStream(); FileUtils.copyInputStreamToFile(conIS, new File(filename)); System.out.println(Messages.getString("EbookDownloader.DownloadingOK")); //$NON-NLS-1$ prefs.put(LAST_SAVED_EBOOK_PREF, i + ""); //$NON-NLS-1$ conIS.close(); } catch (Exception e) { System.out.println(Messages.getString("EbookDownloader.DownloadingKO")); //$NON-NLS-1$ } } } } catch (Exception e) { System.err.println(Messages.getString("EbookDownloader.FatalError")); //$NON-NLS-1$ e.printStackTrace(); } } else { printHelp(); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { URL u = new URL("http://www.java2s.com"); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); int code = uc.getResponseCode(); String response = uc.getResponseMessage(); System.out.println("HTTP/1.x " + code + " " + response); for (int j = 1;; j++) { String header = uc.getHeaderField(j); String key = uc.getHeaderFieldKey(j); if (header == null || key == null) break; System.out.println(uc.getHeaderFieldKey(j) + ": " + header); }/*from ww w . ja v a2 s .c o m*/ InputStream in = new BufferedInputStream(uc.getInputStream()); Reader r = new InputStreamReader(in); int c; while ((c = r.read()) != -1) { System.out.print((char) c); } }
From source file:GcmSender.java
public static void main(String[] ar) { String message = "<Push message string here>"; String to = "<Device token here>"; try {//from w w w. j a v a2 s. c om // 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(); } }
From source file:com.yannick.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pargs=\"MESSAGE[,DEVICE_TOKEN]\""); System.err.println(""); System.err.println(/* w w w . j a v a2 s . co m*/ "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pargs=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pargs=\"<Your_Message>,<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>,<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", args[0].trim()); // Where to send GCM message. if (args.length > 1 && args[1] != null) { jGcmData.put("to", args[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // 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(); } }
From source file:lc.buyplus.gcmsender.GcmSender.java
public static void main(String[] args) throws JSONException { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println(/*from ww w . ja v a 2s. c o m*/ "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", args[0].trim()); // Where to send GCM message. if (args.length > 1 && args[1] != null) { jGcmData.put("to", args[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // 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(); } }
From source file:com.pinch.console.GcmSender.java
public static void main(String[] args) { // if (args.length < 1 || args.length > 2 || args[0] == null) { // System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); // System.err.println(""); // System.err.println("Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + // "specified, the message will only be sent to that device. Otherwise, the message \n" + // "will be sent to all devices subscribed to the \"global\" topic."); // System.err.println(""); // System.err.println("Example (Broadcast):\n" + // "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + // "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); // System.err.println(""); // System.err.println("Example (Unicast):\n" + // "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + // "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); // System.exit(1); // }//from ww w . jav a 2 s. c om try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", "Saurabh Garg signed up!!"); jData.put("title", "New sign up!"); // Where to send GCM message. //if (args.length > 1 && args[1] != null) { jGcmData.put("to", "dOEmVpNPTCY:APA91bEkeYfFMhAraF4d87SJu12oxDElUp6KW1r710KSKeuDpW31Cd5_WExUxT16KNquJ69wwDMlxd-3qoEIeDNJNU1XjyXiXztOqlKglB-zdOlszoXhX9zIYmYNV8d4vWkM0oPwjlk9"); // } else { // jGcmData.put("to", "/topics/global"); // } // What to send in GCM message. jGcmData.put("data", jData); // 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(); } }