Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;//  ww  w .j av  a  2s.c  om
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:Main.java

public static byte[] charArrayToByteArray(char[] buffer) {
    try {/*www .j a  v  a  2  s .  c  o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(baos, ENCODING);
        Reader reader = new CharArrayReader(buffer);
        for (int ch; (ch = reader.read()) != -1;) {
            out.write(ch);
        }
        return baos.toByteArray();
    } catch (Exception ex) {
        return null;
    }
}

From source file:Main.java

public static String request(String url, Map<String, String> cookies, Map<String, String> parameters)
        throws Exception {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
    if (cookies != null && !cookies.isEmpty()) {
        StringBuilder cookieHeader = new StringBuilder();
        for (String cookie : cookies.values()) {
            if (cookieHeader.length() > 0) {
                cookieHeader.append(";");
            }/*from  ww w  . j ava2 s.c o m*/
            cookieHeader.append(cookie);
        }
        connection.setRequestProperty("Cookie", cookieHeader.toString());
    }
    connection.setDoInput(true);
    if (parameters != null && !parameters.isEmpty()) {
        connection.setDoOutput(true);
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(parametersToWWWFormURLEncoded(parameters));
        osw.flush();
        osw.close();
    }
    if (cookies != null) {
        for (Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
            if (headerEntry != null && headerEntry.getKey() != null
                    && headerEntry.getKey().equalsIgnoreCase("Set-Cookie")) {
                for (String header : headerEntry.getValue()) {
                    for (HttpCookie httpCookie : HttpCookie.parse(header)) {
                        cookies.put(httpCookie.getName(), httpCookie.toString());
                    }
                }
            }
        }
    }
    Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringWriter w = new StringWriter();
    char[] buffer = new char[1024];
    int n = 0;
    while ((n = r.read(buffer)) != -1) {
        w.write(buffer, 0, n);
    }
    r.close();
    return w.toString();
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {
    Process proc = null;//from w  w  w. j  a  v  a 2s  .c o  m
    int exitCode = -1;

    if (runAsRoot) {
        proc = Runtime.getRuntime().exec("su");
    } else {
        proc = Runtime.getRuntime().exec("sh");
    }

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {
        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();
    }

    return exitCode;
}

From source file:com.fluidops.iwb.provider.GoogleRefineProvider.java

/**
 * utility to simplify doing POST requests
 * /*from   w w w  .j  av a  2 s .  c  om*/
 * @param url         URL to post to
 * @param parameter      map of parameters to post
 * @return            URLConnection is a state where post parameters have been sent
 * @throws IOException
 * 
 * TODO: move to util class
 */
public static URLConnection doPost(URL url, Map<String, String> parameter) throws IOException {
    URLConnection con = url.openConnection();
    con.setDoOutput(true);

    StringBuilder params = new StringBuilder();
    for (Entry<String, String> entry : parameter.entrySet())
        params.append(StringUtil.urlEncode(entry.getKey())).append("=")
                .append(StringUtil.urlEncode(entry.getValue())).append("&");

    // Send data
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(params.toString());
    wr.flush();
    wr.close();

    return con;
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;//  w  ww  .  j  a  va  2s  . com
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:com.jaspersoft.jasperserver.core.util.StreamUtil.java

public static byte[] compress(String string) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    OutputStreamWriter osw = new OutputStreamWriter(gzos);
    osw.write(string);
    osw.flush();/*from w  w  w .  j  av a2s.com*/
    osw.close();
    return baos.toByteArray();
}

From source file:ilearnrw.utils.ServerHelperClass.java

public static String sendPost(String link, String urlParameters) throws Exception {
    String url = baseUrl + link;//  ww w  .  ja v a  2s.  c  o  m

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));

    con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF8");

    wr.write(urlParameters);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

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

    return response.toString();
}

From source file:com.company.project.core.connector.HttpClientHelper.java

public static String getResponseStringFromConn(HttpURLConnection conn, String payLoad) throws IOException {

    // Send the http message payload to the server.
    if (payLoad != null) {
        conn.setDoOutput(true);/*from   www  .j  a  va 2 s .  c  om*/
        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
        osw.write(payLoad);
        osw.flush();
        osw.close();
    }

    // Get the message response from the server.
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    StringBuffer stringBuffer = new StringBuffer();
    while ((line = br.readLine()) != null) {
        stringBuffer.append(line);
    }

    br.close();

    return stringBuffer.toString();
}

From source file:com.beginner.core.utils.SmsUtil.java

public static String SMS(String postData, String postUrl) {
    try {//from   w  w w  .  j  a  v  a 2 s. c  o  m
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }
        //??
        String line, result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return "";
}