Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

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

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:net.maizegenetics.analysis.imputation.FILLINImputationAccuracy.java

private void accuracyMAFOut() {
    DecimalFormat df = new DecimalFormat("0.########");
    if (this.MAF != null && this.MAFClass != null)
        try {//from w ww . j a  v  a 2  s.  c o  m
            String ext = FilenameUtils.getExtension(this.outFile);
            File outputFile = new File(this.outFile.replace(ext, "MAFAccuracy.txt"));
            DataOutputStream outStream = new DataOutputStream(
                    new BufferedOutputStream(new FileOutputStream(outputFile)));
            outStream.writeBytes(
                    "##\tMAFClass\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumHets\tHetToMinor\tHetToMajor\tCorrectHet\tUnimpHet\tNumMinor\tMinorToMajor\tMinorToHet\tCorrectMinor\t"
                            + "UnimpMinor\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimputedMajor\tr2\n");
            for (int i = 0; i < this.MAFClass.length; i++) {
                outStream
                        .writeBytes("##TotalByImputed\t" + this.MAFClass[i] + "\t"
                                + (this.mafAll[i][0][4] + this.mafAll[i][1][4] + this.mafAll[i][2][4]) + "\t"
                                + (this.mafAll[i][0][4] + this.mafAll[i][1][4] + this.mafAll[i][2][4]
                                        - this.mafAll[i][0][3] - this.mafAll[i][1][3] - this.mafAll[i][2][3])
                                + "\t"
                                + ((this.mafAll[i][0][3] + this.mafAll[i][1][3] + this.mafAll[i][2][3])
                                        / (this.mafAll[i][0][4] + this.mafAll[i][1][4] + this.mafAll[i][2][4]))
                                + "\t" + this.mafAll[i][0][4] + "\t" + this.mafAll[i][0][0] + "\t"
                                + this.mafAll[i][0][1] + "\t" + this.mafAll[i][0][2] + "\t"
                                + this.mafAll[i][0][3] + "\t" + this.mafAll[i][1][4] + "\t"
                                + this.mafAll[i][1][0] + "\t" + this.mafAll[i][1][1] + "\t"
                                + this.mafAll[i][1][2] + "\t" + this.mafAll[i][1][3] + "\t"
                                + this.mafAll[i][2][4] + "\t" + this.mafAll[i][2][0] + "\t"
                                + this.mafAll[i][2][1] + "\t" + this.mafAll[i][2][2] + "\t"
                                + this.mafAll[i][2][3] + "\t" + pearsonR2(this.mafAll[i], false) + "\n");
            }
            outStream.writeBytes(
                    "#MAFClass,Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nMAF\tx\ty\tN\tprop\n");
            for (int i = 0; i < this.MAFClass.length; i++) {
                outStream.writeBytes(this.MAFClass[i] + "\t" + 0 + "\t" + 0 + "\t" + this.mafAll[i][0][0] + "\t"
                        + df.format((this.mafAll[i][0][0])
                                / (this.mafAll[i][0][0] + this.mafAll[i][0][1] + this.mafAll[i][0][2]))
                        + "\n" + this.MAFClass[i] + "\t" + 0 + "\t" + .5 + "\t" + this.mafAll[i][0][1] + "\t"
                        + df.format((this.mafAll[i][0][1])
                                / (this.mafAll[i][0][0] + this.mafAll[i][0][1] + this.mafAll[i][0][2]))
                        + "\n" + this.MAFClass[i] + "\t" + 0 + "\t" + 1 + "\t" + this.mafAll[i][0][2] + "\t"
                        + df.format((this.mafAll[i][0][2])
                                / (this.mafAll[i][0][0] + this.mafAll[i][0][1] + this.mafAll[i][0][2]))
                        + "\n" + this.MAFClass[i] + "\t" + .5 + "\t" + 0 + "\t" + this.mafAll[i][1][0] + "\t"
                        + df.format((this.mafAll[i][1][0])
                                / (this.mafAll[i][1][0] + this.mafAll[i][1][1] + this.mafAll[i][1][2]))
                        + "\n" + this.MAFClass[i] + "\t" + .5 + "\t" + .5 + "\t" + this.mafAll[i][1][1] + "\t"
                        + df.format((this.mafAll[i][1][1])
                                / (this.mafAll[i][1][0] + this.mafAll[i][1][1] + this.mafAll[i][1][2]))
                        + "\n" + this.MAFClass[i] + "\t" + .5 + "\t" + 1 + "\t" + this.mafAll[i][1][2] + "\t"
                        + df.format((this.mafAll[i][1][2])
                                / (this.mafAll[i][1][0] + this.mafAll[i][1][1] + this.mafAll[i][1][2]))
                        + "\n" + this.MAFClass[i] + "\t" + 1 + "\t" + 0 + "\t" + this.mafAll[i][2][0] + "\t"
                        + df.format((this.mafAll[i][2][0])
                                / (this.mafAll[i][2][0] + this.mafAll[i][2][1] + this.mafAll[i][2][2]))
                        + "\n" + this.MAFClass[i] + "\t" + 1 + "\t" + .5 + "\t" + this.mafAll[i][2][1] + "\t"
                        + df.format((this.mafAll[i][2][1])
                                / (this.mafAll[i][2][0] + this.mafAll[i][2][1] + this.mafAll[i][2][2]))
                        + "\n" + this.MAFClass[i] + "\t" + 1 + "\t" + 1 + "\t" + this.mafAll[i][2][2] + "\t"
                        + df.format((this.mafAll[i][2][2])
                                / (this.mafAll[i][2][0] + this.mafAll[i][2][1] + this.mafAll[i][2][2]))
                        + "\n");
            }
            outStream.writeBytes("#Proportion unimputed:\n#MAF\tminor\thet\tmajor\n");
            for (int i = 0; i < this.MAFClass.length; i++) {
                outStream.writeBytes("#" + this.MAFClass[i] + "\t" + this.mafAll[i][0][3] / this.mafAll[i][0][4]
                        + "\t" + this.mafAll[i][1][3] / this.mafAll[i][1][4] + "\t"
                        + this.mafAll[i][2][3] / this.mafAll[i][2][4] + "\n");
            }
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            if (this.verboseOutput)
                System.out.println(e);
        }
}

From source file:net.maizegenetics.analysis.imputation.FILLINImputationAccuracy.java

private void accuracyOut(double time) {
    DecimalFormat df = new DecimalFormat("0.########");
    double r2 = pearsonR2(this.all, this.verboseOutput);
    try {/*from w  w w. j  av  a  2s  .  c om*/
        String ext = FilenameUtils.getExtension(this.outFile);
        File outputFile = new File(this.outFile.replace(ext, "Accuracy.txt"));
        DataOutputStream outStream = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(outputFile)));
        outStream.writeBytes(
                "##Taxon\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumMinor\tCorrectMinor\tMinorToHet\tMinorToMajor\tUnimpMinor"
                        + "\tNumHets\tHetToMinor\tCorrectHet\tHetToMajor\tUnimpHet\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimpMajor\tR2\n");
        outStream.writeBytes("##TotalByImputed\t" + (this.all[0][4] + this.all[1][4] + this.all[2][4]) + "\t"
                + (this.all[0][4]
                        + this.all[1][4] + this.all[2][4] - this.all[0][3] - this.all[1][3] - this.all[2][3])
                + "\t"
                + ((this.all[0][3] + this.all[1][3] + this.all[2][3])
                        / (this.all[0][4] + this.all[1][4] + this.all[2][4]))
                + "\t" + this.all[0][4] + "\t" + this.all[0][0] + "\t" + this.all[0][1] + "\t" + this.all[0][2]
                + "\t" + this.all[0][3] + "\t" + this.all[1][4] + "\t" + this.all[1][0] + "\t" + this.all[1][1]
                + "\t" + this.all[1][2] + "\t" + this.all[1][3] + "\t" + this.all[2][4] + "\t" + this.all[2][0]
                + "\t" + this.all[2][1] + "\t" + this.all[2][2] + "\t" + this.all[2][3] + "\t" + r2 + "\n");
        outStream.writeBytes("#Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nx\ty\tN\tprop\n" + 0
                + "\t" + 0 + "\t" + this.all[0][0] + "\t"
                + df.format((this.all[0][0]) / (this.all[0][0] + this.all[0][1] + this.all[0][2])) + "\n" + 0
                + "\t" + .5 + "\t" + this.all[0][1] + "\t"
                + df.format((this.all[0][1]) / (this.all[0][0] + this.all[0][1] + this.all[0][2])) + "\n" + 0
                + "\t" + 1 + "\t" + this.all[0][2] + "\t"
                + df.format((this.all[0][2]) / (this.all[0][0] + this.all[0][1] + this.all[0][2])) + "\n" + .5
                + "\t" + 0 + "\t" + this.all[1][0] + "\t"
                + df.format((this.all[1][0]) / (this.all[1][0] + this.all[1][1] + this.all[1][2])) + "\n" + .5
                + "\t" + .5 + "\t" + this.all[1][1] + "\t"
                + df.format((this.all[1][1]) / (this.all[1][0] + this.all[1][1] + this.all[1][2])) + "\n" + .5
                + "\t" + 1 + "\t" + this.all[1][2] + "\t"
                + df.format((this.all[1][2]) / (this.all[1][0] + this.all[1][1] + this.all[1][2])) + "\n" + 1
                + "\t" + 0 + "\t" + this.all[2][0] + "\t"
                + df.format((this.all[2][0]) / (this.all[2][0] + this.all[2][1] + this.all[2][2])) + "\n" + 1
                + "\t" + .5 + "\t" + this.all[2][1] + "\t"
                + df.format((this.all[2][1]) / (this.all[2][0] + this.all[2][1] + this.all[2][2])) + "\n" + 1
                + "\t" + 1 + "\t" + this.all[2][2] + "\t"
                + df.format((this.all[2][2]) / (this.all[2][0] + this.all[2][1] + this.all[2][2])) + "\n");
        outStream.writeBytes("#Proportion unimputed:\n#minor <- " + this.all[0][3] / this.all[0][4]
                + "\n#het<- " + this.all[1][3] / this.all[1][4] + "\n#major<- "
                + this.all[2][3] / this.all[2][4] + "\n");
        outStream.writeBytes("#Time to impute and calculate accuracy: " + time + " seconds");
        if (this.verboseOutput)
            System.out.println(
                    "##Taxon\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumMinor\tCorrectMinor\tMinorToHet\tMinorToMajor\tUnimpMinor"
                            + "\tNumHets\tHetToMinor\tCorrectHet\tHetToMajor\tUnimpHet\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimpMajor\tR2");
        if (this.verboseOutput)
            System.out.println("TotalByImputed\t" + (this.all[0][4] + this.all[1][4] + this.all[2][4]) + "\t"
                    + (this.all[0][4] + this.all[1][4] + this.all[2][4] - this.all[0][3] - this.all[1][3]
                            - this.all[2][3])
                    + "\t"
                    + ((this.all[0][3] + this.all[1][3] + this.all[2][3])
                            / (this.all[0][4] + this.all[1][4] + this.all[2][4]))
                    + "\t" + this.all[0][4] + "\t" + this.all[0][0] + "\t" + this.all[0][1] + "\t"
                    + this.all[0][2] + "\t" + this.all[0][3] + "\t" + this.all[1][4] + "\t" + this.all[1][0]
                    + "\t" + this.all[1][1] + "\t" + this.all[1][2] + "\t" + this.all[1][3] + "\t"
                    + this.all[2][4] + "\t" + this.all[2][0] + "\t" + this.all[2][1] + "\t" + this.all[2][2]
                    + "\t" + this.all[2][3] + "\t" + r2);
        if (this.verboseOutput)
            System.out.println("Proportion unimputed:\nminor: " + this.all[0][3] / this.all[0][4] + "\nhet: "
                    + this.all[1][3] / this.all[1][4] + "\nmajor: " + this.all[2][3] / this.all[2][4]);
        if (this.verboseOutput)
            System.out.println("#Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nx\ty\tN\tprop\n" + 0
                    + "\t" + 0 + "\t" + this.all[0][0] + "\t"
                    + (this.all[0][0]) / (this.all[0][0] + this.all[0][1] + this.all[0][2]) + "\n" + 0 + "\t"
                    + .5 + "\t" + this.all[0][1] + "\t"
                    + (this.all[0][1]) / (this.all[0][0] + this.all[0][1] + this.all[0][2]) + "\n" + 0 + "\t"
                    + 1 + "\t" + this.all[0][2] + "\t"
                    + (this.all[0][2]) / (this.all[0][0] + this.all[0][1] + this.all[0][2]) + "\n" + .5 + "\t"
                    + 0 + "\t" + this.all[1][0] + "\t"
                    + (this.all[1][0]) / (this.all[1][0] + this.all[1][1] + this.all[1][2]) + "\n" + .5 + "\t"
                    + .5 + "\t" + this.all[1][1] + "\t"
                    + (this.all[1][1]) / (this.all[1][0] + this.all[1][1] + this.all[1][2]) + "\n" + .5 + "\t"
                    + 1 + "\t" + this.all[1][2] + "\t"
                    + (this.all[1][2]) / (this.all[1][0] + this.all[1][1] + this.all[1][2]) + "\n" + 1 + "\t"
                    + 0 + "\t" + this.all[2][0] + "\t"
                    + (this.all[2][0]) / (this.all[2][0] + this.all[2][1] + this.all[2][2]) + "\n" + 1 + "\t"
                    + .5 + "\t" + this.all[2][1] + "\t"
                    + (this.all[2][1]) / (this.all[2][0] + this.all[2][1] + this.all[2][2]) + "\n" + 1 + "\t"
                    + 1 + "\t" + this.all[2][2] + "\t"
                    + (this.all[2][2]) / (this.all[2][0] + this.all[2][1] + this.all[2][2]) + "\n");
        outStream.close();
    } catch (Exception e) {
        if (this.verboseOutput)
            System.out.println(e);
    }
}

From source file:copter.ServerConnection.java

private String postToServer(String postUrl, Map<String, String> parameters) {
    String serverHost = Config.getInstance().getString("main", "server_host");
    URL url;//from  w ww.  j  a  va2  s .c o  m
    try {
        url = new URL("http://" + serverHost + postUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        //con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        String urlParameters = "";
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String paramName = entry.getKey();
            String paramValue = entry.getValue();
            String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
            urlParameters += paramName + "=" + encodedParamValue + "&";
        }
        if (urlParameters.endsWith("&")) {
            urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
        }
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        //logger.log("\nSending 'POST' request to URL : " + url);
        //logger.log("Post parameters : " + urlParameters);
        //logger.log("Response Code : " + responseCode);

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

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String serverResponse = response.toString();
        return serverResponse;
    } catch (Exception ex) {
        logger.log(ex.getMessage());
        return null;
    }
}

From source file:com.qcloud.PicCloud.java

/**
 * Download /*from  ww w. j a  v a2 s.c  om*/
 * @param url           
 * @param fileName    ?
 * @return ?0?
 */
public int download(String url, String fileName) {
    JSONObject rspData = null;
    try {
        String rsp = mClient.get(url, null, null);
        File file = new File(fileName);
        DataOutputStream ops = new DataOutputStream(new FileOutputStream(file));
        ops.writeBytes(rsp);
        ops.close();
    } catch (Exception e) {
        return setError(-1, "url exception, e=" + e.toString());
    }

    return setError(0, "success");
}

From source file:edu.ku.brc.specify.tools.StrLocaleFile.java

/**
 * Save as Ascii./*w w w . j av a  2  s. c  o m*/
 */
public boolean save() {
    FileOutputStream fos = null;
    DataOutputStream dos = null;

    try {
        fos = new FileOutputStream(dstPath);
        dos = new DataOutputStream(fos);//, "UTF-8");

        for (StrLocaleEntry entry : items) {
            String str = "";
            if (entry.getKey() == null) {

            } else if (entry.getKey().equals("#")) {
                str = entry.getSrcStr();
            } else {
                str = entry.getKey() + "=" + (entry.getDstStr() == null ? "" : entry.getDstStr());
            }

            str += '\n';
            dos.writeBytes(str);
        }
        dos.flush();
        dos.close();
        return true;

    } catch (Exception e) {
        System.out.println("e: " + e);
    }
    return false;
}

From source file:net.larry1123.elec.util.logger.EELogger.java

/**
 * Will Log a StackTrace and Post it on to http://paste.larry1123.net/
 * Will return true if it was able to post and false if it was not able to post
 * Throws with the Level given// www  .j av a 2  s .  c  o  m
 *
 * @param lvl     The Level to be thrown with
 * @param message Message to be Logged
 * @param thrown  Throwable Error To be logged
 *
 * @return {@code true} if paste was made of stackTrace; {@code falase} if it failed for any reason
 */
public boolean logStackTraceToPasteBin(Level lvl, String message, Throwable thrown) {
    if (getConfig().isPastingAllowed()) {
        EELogger eeLogger = FactoryManager.getFactoryManager().getEELoggerFactory().getSubLogger("EEUtil",
                "PasteBinLog");
        try {
            URL url = new URL("https://paste.larry1123.net/api/xml/create");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "data=" + "[" + lvl.getName() + "] " + message + "\n"
                    + org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(thrown);
            urlParameters += "&";
            String title = "[" + lvl.getName() + "] " + message;
            urlParameters += "title=" + (title.length() > 30 ? title.substring(0, 30) : title);
            urlParameters += "&";
            urlParameters += "language=Java";

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            if (con.getResponseCode() == 200) {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document document = dBuilder.parse(con.getInputStream());
                document.getDocumentElement().normalize();

                NodeList nodeList = document.getElementsByTagName("id");
                Node node = nodeList.item(0);
                String id = node.getTextContent();
                eeLogger.info("Logger " + getName() + ": https://paste.larry1123.net/" + id);
                return true;
            }
            return false;
        } catch (MalformedURLException e) {
            eeLogger.error("Failed to send: Malformed", e);
            return false;
        } catch (IOException e) {
            eeLogger.error("Failed to send: IOException", e);
            return false;
        } catch (ParserConfigurationException e) {
            eeLogger.error("Failed to send: ParserConfigurationException", e);
            return false;
        } catch (SAXException e) {
            eeLogger.error("Failed to send: SAXException", e);
            return false;
        }
    } else {
        return false;
    }
}

From source file:com.tandong.sa.aq.AbstractAjaxCallback.java

private static void writeData(DataOutputStream dos, String name, String filename, InputStream is)
        throws IOException {

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\";" + " filename=\"" + filename + "\""
            + lineEnd);/*  ww w .  j av a 2 s .  c  o  m*/
    dos.writeBytes(lineEnd);

    AQUtility.copy(is, dos);

    dos.writeBytes(lineEnd);

}

From source file:com.retroteam.studio.retrostudio.EditorLandscape.java

/**
 * Write the 8bit PCM audio to the wav file format to the public music dir.
 * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
 * @param proj/*from w  w w . j  a va  2s. c om*/
 * @param filename
 */

private void exportAsWav(Project proj, String filename) {
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
                filename + ".wav");
        DataOutputStream os = new DataOutputStream(new FileOutputStream(file));

        // get project length
        int pLength = proj.export().getBytes().length;

        os.writeBytes("RIFF"); // Chunk ID 'RIFF'
        os.write(intToByteArray(36 + pLength), 0, 4); //file size
        os.writeBytes("WAVE"); // Wave ID
        os.writeBytes("fmt "); // Chunk ID 'fmt '
        os.write(intToByteArray(16), 0, 4); // chunk size
        os.write(intToByteArray(1), 0, 2); // pcm audio
        os.write(intToByteArray(1), 0, 2); // mono
        os.write(intToByteArray(8000), 0, 4); // samples/sec
        os.write(intToByteArray(pLength), 0, 4); // bytes/sec
        os.write(intToByteArray(1), 0, 2); // 1 byte/sample
        os.write(intToByteArray(8), 0, 2); // 8 bits/sample
        os.writeBytes("data"); // Chunk ID 'data'
        os.write(intToByteArray(pLength), 0, 4); // size of data chunk
        os.write(proj.export().getBytes()); // write the data
        os.close();
        Toast.makeText(this, "Saved file to: " + file.getPath(), Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(this, "IOException while saving project.", Toast.LENGTH_SHORT).show();
    }
}

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpSendPostWithAuth(String url, String body, Map<String, String> headers, String username,
        String password) throws IOException {

    String userPassword = username + ":" + password;
    String encoding = Base64.encodeBase64String(userPassword.getBytes());
    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // add request method
    con.setRequestMethod("POST");

    con.setRequestProperty("Authorization", "Basic " + encoding);

    // add request headers
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }/*  w  w  w. j ava2s.co  m*/

    }

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();

    // con.connect();

    int responseCode = con.getResponseCode();
    logger.debug("Send POST http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        response = null;

    }
    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);
    if (response == null) {
        restResponse.setResponse(null);
    } else {
        restResponse.setResponse(response.toString());
    }

    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();
    return restResponse;

}

From source file:TimestreamsTests.java

/**
 * Performs HTTP post for a given URL/*from   ww w.j  a  va2 s.c o  m*/
 * 
 * @param url
 *            is the URL to get
 * @param params
 *            is a URL encoded string in the form x=y&a=b...
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doPost(URL url, String params) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();
        Map<String, List<String>> responseHeaderFields = connection.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            System.out.println(response);
        }
        return responseHeaderFields;
    } catch (IOException e1) {
        fail("Post " + url + " failed: " + e1.getLocalizedMessage());
    }

    return null;
}