Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * Post??web??,?utf-8/*w ww  .  j  av a2s .c  o m*/
 * 
 * ?UTF8
 * 
 * @param actionUrl
 * @param params
 * @param timeout   
 * @return
 * @throws InvalidParameterException
 * @throws NetWorkException
 * @throws IOException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws Exception
 */
public static String post(String url, Map<String, String> params, int timeout)
        throws IOException, IllegalArgumentException, IllegalAccessException {
    if (url == null || url.equals(""))
        throw new IllegalArgumentException("url ");
    if (params == null)
        throw new IllegalArgumentException("params ?");
    if (url.indexOf('?') > 0) {
        url = url
                + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    } else {
        url = url
                + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    }

    String sb2 = "";
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";
    // try {
    URL uri = new URL(url);
    HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection();
    // 
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(timeout);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    conn.setSSLSocketFactory(ssf);
    conn.setHostnameVerifier(HOSTNAME_VERIFIER);

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(PREFIX);
        sb.append(BOUNDARY);
        sb.append(LINEND);
        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
        sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        sb.append(LINEND);
        sb.append(entry.getValue());
        sb.append(LINEND);
    }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(sb.toString().getBytes("UTF-8"));
    InputStream in = null;

    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
    outStream.write(end_data);
    outStream.flush();

    int res = conn.getResponseCode();
    if (res == 200) {
        in = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            sb2 = sb2 + line;
        }
    }
    outStream.close();
    conn.disconnect();
    return sb2;
}

From source file:com.theonespy.util.Util.java

public static void disableMobileData() {
    Util.Log("Disable mobile data");

    try {//  w  w w. j  ava  2s. co m
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        outputStream.writeBytes("svc data disable\n ");
        outputStream.flush();

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * //ww  w .  ja  va  2  s.co m
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:BihuHttpUtil.java

/**
 * ??HTTPJSON?//w  w  w  . j  a va  2s.c  o m
 * @param url
 * @param jsonStr
 */
public static String sendPostForJson(String url, String jsonStr) {
    StringBuffer sb = new StringBuffer("");
    try {
        //
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        //POST
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(jsonStr.getBytes("UTF-8"));//???
        out.flush();
        out.close();
        //??
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // 
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:com.sinpo.xnfc.nfc.Util.java

public static String execRootCmd(String cmd) {
    String result = "";
    DataOutputStream dos = null;
    DataInputStream dis = null;//from w w w  .  ja v  a  2s  . c  o m

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        dos.writeBytes(cmd + "\n");
        dos.flush();
        dos.writeBytes("exit\n");
        dos.flush();
        String line = null;
        while ((line = dis.readLine()) != null) {
            result += line + "\r\n";
        }
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:Main.java

public static void makeInternalCopy(Context c, String path, int resource) {
    InputStream is = c.getResources().openRawResource(resource);
    try {/* w  ww .j  a va2s .  c  om*/

        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        File sniff = new File(path);
        if (sniff.exists()) {
            os.writeBytes("rm " + path + "\n");
        }
        byte[] bytes = new byte[is.available()];

        FileOutputStream setdbOutStream = new FileOutputStream(path);
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(bytes);

        setdbOutStream.write(bytes);
        setdbOutStream.close();

        os.writeBytes("chmod 777 " + path + "\n");
        os.writeBytes("exit\n");
        os.flush();
    } catch (Exception e) {
        //           Toast.makeText(c, "Error Copying file: " + e.toString(),Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

}

From source file:com.sinpo.xnfc.nfc.Util.java

/**
 * ??? Root??(ROOT??)/*from  ww w.  j a va  2s.co m*/
 *
 * @return ?/??Root??
 */
public static boolean upgradeRootPermission(String pkgCodePath) {
    Process process = null;
    DataOutputStream os = null;
    try {
        String cmd = "chmod 777 " + pkgCodePath;
        process = Runtime.getRuntime().exec("su"); //?root??
        os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(cmd + "\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
            process.destroy();
        } catch (Exception e) {
        }
    }
    return true;
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;/*  ww  w.ja v a2  s  .c  om*/
    URL url = new URL(urlstr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //       connection.setRequestProperty("token",token);
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.connect();

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    String content = "";
    if (params != null && params.size() > 0) {
        for (int i = 0; i < params.size(); i++) {
            content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8")
                    + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
        }
        out.writeBytes(content.substring(1));
    }

    out.flush();
    out.close();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:Main.java

public static String runCommand(String[] commands) {
    DataOutputStream outStream = null;
    DataInputStream responseStream;
    try {/*ww  w. j  ava 2 s .c o  m*/
        ArrayList<String> logs = new ArrayList<String>();
        Process process = Runtime.getRuntime().exec("su");
        Log.i(TAG, "Executed su");
        outStream = new DataOutputStream(process.getOutputStream());
        responseStream = new DataInputStream(process.getInputStream());

        for (String single : commands) {
            Log.i(TAG, "Command = " + single);
            outStream.writeBytes(single + "\n");
            outStream.flush();
            if (responseStream.available() > 0) {
                Log.i(TAG, "Reading response");
                logs.add(responseStream.readLine());
                Log.i(TAG, "Read response");
            } else {
                Log.i(TAG, "No response available");
            }
        }
        outStream.writeBytes("exit\n");
        outStream.flush();
        String log = "";
        for (int i = 0; i < logs.size(); i++) {
            log += logs.get(i) + "\n";
        }
        Log.i(TAG, "Execution compeleted");
        return log;
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }
    return null;
}

From source file:disko.DU.java

public static String request(String targetUrl, String method, String text, String contentType)
        throws Exception {
    URL url = new URL(targetUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (method != null)
        conn.setRequestMethod(method);/*from w  w w . jav a 2s  .  c o m*/

    if (contentType != null)
        conn.setRequestProperty("Content-Type", contentType);

    if (text != null) {
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.getOutputStream().write(text.getBytes());
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(text.getBytes());
        out.flush();
        out.close();
    }

    if (conn.getResponseCode() != 200)
        throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode());

    StringBuffer responseBuffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    String eol = new String(new byte[] { 13 });
    while ((line = in.readLine()) != null) {
        responseBuffer.append(line);
        responseBuffer.append(eol);
    }
    in.close();

    return responseBuffer.toString();
}