Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

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);//  ww w.ja  va2  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: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.  ja  v a 2s  .c om*/
    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:GcmSender.java

public static void main(String[] ar) {
    String message = "<Push message string here>";
    String to = "<Device token here>";
    try {//from  ww  w. ja  va2 s . com
        // 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:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java

public static void main(String[] args) {
    try {// ww  w . j a  va2s.  co  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: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(/*from w w w  .  ja va2s.  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 -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(/* w  ww  . j ava 2 s. 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  w  w w . ja va2s.  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();
    }
}

From source file:gcm.play.android.samples.com.gcmquickstart.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 -Pargs=\"MESSAGE[,DEVICE_TOKEN]\"");
        System.err.println("");
        System.err.println(// ww w  .  jav a2 s .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 -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:OCRRestAPI.java

public static void main(String[] args) throws Exception {
    /*//w ww.ja  va 2  s.c om
              
         Sample project for OCRWebService.com (REST API).
         Extract text from scanned images and convert into editable formats.
         Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code
            
     */

    // Provide your user name and license code
    String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D";
    String user_name = "FERGOID";

    /*
            
      You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide
             
      Input parameters:
             
     [language]      - Specifies the recognition language. 
                  This parameter can contain several language names separated with commas. 
                    For example "language=english,german,spanish".
               Optional parameter. By default:english
            
     [pagerange]     - Enter page numbers and/or page ranges separated by commas. 
               For example "pagerange=1,3,5-12" or "pagerange=allpages".
                    Optional parameter. By default:allpages
             
      [tobw]           - Convert image to black and white (recommend for color image and photo). 
               For example "tobw=false"
                    Optional parameter. By default:false
             
      [zone]          - Specifies the region on the image for zonal OCR. 
               The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. 
               This parameter can contain several zones separated with commas. 
                 For example "zone=0:0:100:100,50:50:50:50"
                    Optional parameter.
              
      [outputformat]  - Specifies the output file format.
                    Can be specified up to two output formats, separated with commas.
               For example "outputformat=pdf,txt"
                    Optional parameter. By default:doc
            
      [gettext]      - Specifies that extracted text will be returned.
               For example "tobw=true"
                    Optional parameter. By default:false
            
       [description]  - Specifies your task description. Will be returned in response.
                    Optional parameter. 
            
            
     !!!!  For getting result you must specify "gettext" or "outputformat" !!!!  
            
    */

    // Build your OCR:

    // Extraction text with English language
    String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";

    // Extraction text with English and German language using zonal OCR
    ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400";

    // Convert first 5 pages of multipage document into doc and txt
    // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt";

    // Full path to uploaded document
    String filePath = "sarah-morgan.jpg";

    byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

    URL url = new URL(ocrURL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Authorization",
            "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes()));

    // Specify Response format to JSON or XML (application/json or application/xml)
    connection.setRequestProperty("Content-Type", "application/json");

    connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

    int httpCode;
    try (OutputStream stream = connection.getOutputStream()) {

        // Send POST request
        stream.write(fileContent);
        stream.close();
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    httpCode = connection.getResponseCode();

    System.out.println("HTTP Response code: " + httpCode);

    // Success request
    if (httpCode == HttpURLConnection.HTTP_OK) {
        // Get response stream
        String jsonResponse = GetResponseToString(connection.getInputStream());

        // Parse and print response from OCR server
        PrintOCRResponse(jsonResponse);
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        System.out.println("OCR Error Message: Unauthorizied request");
    } else {
        // Error occurred
        String jsonResponse = GetResponseToString(connection.getErrorStream());

        JSONParser parser = new JSONParser();
        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

        // Error message
        System.out.println("Error Message: " + jsonObj.get("ErrorMessage"));
    }

    connection.disconnect();

}

From source file:com.pixa.gcmsender.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(//from  www. j  av  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();
        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();
    }
}