Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

In this page you can find the example usage for java.io DataOutputStream DataOutputStream.

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:pushandroid.POST2GCM.java

public static void post(Content content) {

    try {/* ww  w .j a  va 2s .  c om*/

        // 1. URL
        URL url = new URL(URL);

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body
        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public void run() {
    try {/*w ww. j a v a  2  s.  com*/
        Socket client = serverSocket.accept();

        DataInputStream in = new DataInputStream(client.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(client.getOutputStream());

        while (true) {
            String message = in.readUTF();
            System.out.println(message);
            System.out.print("Enter response: ");
            String response = console.readLine();

            out.writeUTF(response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String uploadFile(File file, String RequestURL) {
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data";

    try {/*from w  w w  .j  a  v  a  2 s  . c o  m*/
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        if (file != null) {

            OutputStream outputSteam = conn.getOutputStream();

            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            int res = conn.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                return SUCCESS;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return FAILURE;
}

From source file:MainClass.java

public NumberProducer(OutputStream out, int howMany) {
    theOutput = new DataOutputStream(out);
    this.howMany = howMany;
}

From source file:Main.java

public static String postMultiPart(String urlTo, String post, String filepath, String filefield)
        throws ParseException, IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    try {/*from   w  w w .ja va2 s .c  o m*/
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + q[idx] + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        // Upload POST Data
        String[] posts = post.split("&");
        int max = posts.length;
        for (int i = 0; i < max; i++) {
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            String[] kv = posts[i].split("=");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(kv[1]);
            outputStream.writeBytes(lineEnd);
        }

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();
        result = convertStreamToString(inputStream);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        Log.e("MultipartRequest", "Multipart Form Upload Error");
        e.printStackTrace();
        return "error";
    }
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) {
    try {/*  w w w  .j  ava2  s . c o  m*/
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipartFiles(out, vars, files);

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        return "Encoding exception: " + e;
    } catch (IOException e) {
        return "IOException: " + e;
    } catch (IllegalStateException e) {
        return "IllegalState: " + e;
    }
}

From source file:Main.java

public void run() {
    while (true) {
        try {//from  w w  w.  j a  va  2s .c  om
            System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();

            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());

            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");

            server.close();
        } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }
}

From source file:com.awcoleman.ExampleJobSummaryLogWithOutput.utility.CreateBinaryDatafile.java

public CreateBinaryDatafile(int numrecs) throws IOException {

    Random rangen = new Random();
    long recid = 0;
    try (DataOutputStream out = new DataOutputStream(new FileOutputStream("/tmp/sampleDatafile.bin"));) {

        for (int ii = 0; ii < numrecs; ii++) {
            out.writeUTF(RandomStringUtils.randomAlphabetic(10));
            out.writeLong(++recid);//ww  w.j  a v  a  2s . c  o  m
            out.writeInt(rangen.nextInt(32));
            out.writeInt(rangen.nextInt(3600));
            out.writeUTF(generateDatetime());
        }
    }
}

From source file:Main.java

public static String httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }/*from  w  w w.j  a  va 2s  .c  o m*/

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:Main.java

public static int execRootCmdSilent(String cmd) {
    try {//from w ww. j  a v  a  2 s  . c  o m
        Process p = Runtime.getRuntime().exec("su ");
        Object obj = p.getOutputStream();
        DataOutputStream dOutStream = new DataOutputStream((OutputStream) obj);
        String str = String.valueOf(cmd);
        obj = str + "\n";
        dOutStream.writeBytes((String) obj);
        dOutStream.flush();
        dOutStream.writeBytes("exit\n");
        dOutStream.flush();
        p.waitFor();
        int result = p.exitValue();
        return (Integer) result;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}