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:BRHInit.java

public JSONObject json_rpc(String method, JSONArray params) throws Exception {
    URLConnection conn = rpc_url.openConnection();
    if (cookie != null)
        conn.addRequestProperty("cookie", cookie);

    JSONObject request = new JSONObject();

    request.put("id", false);
    request.put("method", method);
    request.put("params", params);

    conn.setDoOutput(true);/*from w w  w .  j  a va 2 s  .c  o  m*/
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    try {
        wr.write(request.toString());
        wr.flush();
    } finally {
        wr.close();
    }

    // Get the response
    InputStreamReader rd = new InputStreamReader(conn.getInputStream());
    try {
        JSONTokener tokener = new JSONTokener(rd);
        return (JSONObject) tokener.nextValue();
    } finally {
        rd.close();
    }
}

From source file:game.Clue.JerseyClient.java

public void sendPOST() {
    System.out.println("POST method called");
    try {/*  www. j  a v a  2  s . c  o  m*/

        JSONObject jsonObject = new JSONObject("{player:Brian}");
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("POST", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        System.out.println(jsonObject.toString());
        out.write("{" + jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

    } catch (Exception e) {
        System.out.println("\nError while calling REST POST Service");
        System.out.println(e);
    }

}

From source file:com.cloudera.learnavro.test.GenerateTestAvro.java

/**
 *//*  www  .j  a v  a 2s.  co m*/
void emitSchema(File outSchema, Schema schema) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(outSchema)));
    try {
        out.write(schema.toString(true));
    } finally {
        out.close();
    }
}

From source file:com.rapleaf.api.personalization.RapleafApi.java

protected String bulkJsonResponse(String urlStr, String list) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection handle = (HttpURLConnection) url.openConnection();
    handle.setRequestProperty("User-Agent", getUserAgent());
    handle.setRequestProperty("Content-Type", "application/json");
    handle.setConnectTimeout(timeout);//from  w  w w . jav a2  s.  com
    handle.setReadTimeout(bulkTimeout);
    handle.setDoOutput(true);
    handle.setRequestMethod("POST");
    OutputStreamWriter wr = new OutputStreamWriter(handle.getOutputStream());
    wr.write(list);
    wr.flush();
    BufferedReader rd = new BufferedReader(new InputStreamReader(handle.getInputStream()));
    String line = rd.readLine();
    StringBuilder sb = new StringBuilder();
    while (line != null) {
        sb.append(line);
        line = rd.readLine();
    }
    wr.close();
    rd.close();

    int responseCode = handle.getResponseCode();
    if (responseCode < 200 || responseCode > 299) {
        throw new Exception("Error Code " + responseCode + ": " + sb.toString());
    }

    return sb.toString();
}

From source file:com.amastigote.xdu.query.module.WaterAndElectricity.java

private Document getPage(String output_data, String host_suffix) throws IOException {
    URL url = new URL(HOST + host_suffix);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setInstanceFollowRedirects(false);
    httpURLConnection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + ASP_dot_NET_SessionId);

    httpURLConnection.connect();/*from w ww  .java2 s.c om*/
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(output_data);
    outputStreamWriter.flush();
    outputStreamWriter.close();
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection.getInputStream()));

    String temp;
    String htmlPage = "";
    while ((temp = bufferedReader.readLine()) != null)
        htmlPage += temp;

    bufferedReader.close();
    httpURLConnection.disconnect();

    htmlPage = htmlPage.replaceAll("&nbsp;", " ");

    return Jsoup.parse(htmlPage);
}

From source file:com.google.firebase.auth.migration.AuthMigrator.java

private Task<String> exchangeToken(final String legacyToken) {
    if (legacyToken == null) {
        return Tasks.forResult(null);
    }//from w w w  .j ava 2  s  .c om
    return Tasks.call(Executors.newCachedThreadPool(), new Callable<String>() {
        @Override
        public String call() throws Exception {
            JSONObject postBody = new JSONObject();
            postBody.put("token", legacyToken);
            HttpURLConnection connection = (HttpURLConnection) exchangeEndpoint.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            try {
                osw.write(postBody.toString());
                osw.flush();
            } finally {
                osw.close();
            }
            int responseCode = connection.getResponseCode();

            InputStream is;
            if (responseCode >= 400) {
                is = connection.getErrorStream();
            } else {
                is = connection.getInputStream();
            }
            try {
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int numRead = 0;
                while ((numRead = is.read(buffer)) >= 0) {
                    baos.write(buffer, 0, numRead);
                }
                JSONObject resultObject = new JSONObject(new String(baos.toByteArray()));
                if (responseCode != 200) {
                    throw new FirebaseWebRequestException(
                            resultObject.getJSONObject("error").getString("message"), responseCode);
                }
                return resultObject.getString("token");
            } finally {
                is.close();
            }
        }
    });
}

From source file:com.solidmaps.webapp.xml.GenerateFederalMapsServiceImpl.java

private MapProductEntity generateAndSaveFile(String map, CompanyEntity company, String monthYear,
        UserEntity userInsert) throws Exception {

    StringBuilder fileName = new StringBuilder();
    fileName.append("M").append(DateUtils.getYear(monthYear))
            .append(DateUtils.getMonthName(monthYear).substring(0, 3).toUpperCase())
            .append(NumberUtils.clear(company.getCnpj())).append(".txt");

    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(FILE_PATH + fileName.toString()),
            "UTF-8");

    out.write(map);
    out.close();// w ww  . jav a2  s. com

    MapProductEntity mapProduct = this.saveMapProducts(fileName.toString(), company, monthYear, userInsert);

    return mapProduct;

}

From source file:com.doomy.padlock.MainActivity.java

public void androidDebugBridge(String mPort) {
    Runtime mRuntime = Runtime.getRuntime();
    Process mProcess = null;//from  w  w  w  .j a v  a 2 s. c o m
    OutputStreamWriter mWrite = null;

    try {
        mProcess = mRuntime.exec("su");
        mWrite = new OutputStreamWriter(mProcess.getOutputStream());
        mWrite.write("setprop service.adb.tcp.port " + mPort + "\n");
        mWrite.flush();
        mWrite.write("stop adbd\n");
        mWrite.flush();
        mWrite.write("start adbd\n");
        mWrite.flush();
        mWrite.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.votingcentral.services.maxmind.MaxMindGeoLocationService.java

public MaxMindLocationTO getLocation(String ipAddress) {
    MaxMindLocationTO mto = new MaxMindLocationTO();
    String specificData = data + FastURLEncoder.encode(ipAddress, "UTF-8");
    URL url;//from   w  w  w.ja  va  2 s.  c o m
    OutputStreamWriter wr = null;
    BufferedReader rd = null;
    try {
        url = new URL(surl);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(specificData);
        wr.flush();
        // Get the response
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            String[] values = StringUtils.split(line, ",");
            int maxIndex = values.length - 1;
            if (maxIndex >= 0) {
                mto.setISO3166TwoLetterCountryCode(values[0]);
            }
            if (maxIndex >= 1) {
                mto.setRegionCode(values[1]);
            }
            if (maxIndex >= 2) {
                mto.setCity(values[2]);
            }
            if (maxIndex >= 3) {
                mto.setPostalCode(values[3]);
            }
            if (maxIndex >= 4) {
                mto.setLatitude(values[4]);
            }
            if (maxIndex >= 5) {
                mto.setLongitude(values[5]);
            }
            if (maxIndex >= 6) {
                mto.setMetropolitanCode(values[6]);
            }
            if (maxIndex >= 7) {
                mto.setAreaCode(values[7]);
            }
            if (maxIndex >= 8) {
                mto.setIsp(values[8]);
            }
            if (maxIndex >= 9) {
                mto.setOranization(values[9]);
            }
            if (maxIndex >= 10) {
                mto.setError(MaxMindErrorsEnum.get(values[10]));
            }
        }
    } catch (MalformedURLException e) {
        log.fatal("Issue calling Maxmind", e);
        mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
    } catch (IOException e) {
        log.fatal("Issue reading Maxmind", e);
        mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e1) {
                log.fatal("Issue closing Maxmind", e1);
                mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
            }
        }
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e1) {
                log.fatal("Issue closing Maxmind", e1);
                mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
            }
        }
    }
    return mto;
}

From source file:com.example.httpjson.AppEngineClient.java

public void put(URL uri, Map<String, List<String>> headers, byte[] body) {
    PUT put = new PUT(uri, headers, body);

    URL url = null;//ww  w .  j  av a  2  s  .  c o  m
    try {
        url = new URL("http://www.example.com/resource");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpURLConnection httpCon = null;
    try {
        httpCon = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("PUT");
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write("Resource content from PUT!!! ");
        out.close();
        httpCon.getInputStream();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}