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:prince.app.ccm.tools.Task.java

private void sendPost(String url, String postParams) throws Exception {

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

    // Acts like a browser
    conn.setUseCaches(false);//from   w  w  w  . j a v a  2  s.com
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Host", "www.iglesiamallorca.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8,es;q=0.6,ca;q=0.4");

    if (cookies != null) {
        for (String cookie : this.cookies) {
            conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
        }
    }
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Referer", log);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(postParams);
    wr.flush();
    wr.close();

    Log.d(TAG, "sendPost: " + conn.getResponseCode());

    int responseCode = conn.getResponseCode();

    if (conn.getHeaderField("Cache-Control") == null) {
        Log.e(TAG, "An error occurred");
    } else {
        Log.e(TAG, "Everything worked out well");
    }

    Log.e(TAG, conn.getHeaderFields().toString());

    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + postParams);
    System.out.println("Response Code : " + responseCode);

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

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    // System.out.println(response.toString());

    Log.d(TAG, "Done in sendPost");

}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

protected boolean uploadFile(File fileToUpload) {
    String lineEnding = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    boolean success = true;
    HttpURLConnection connection = null;
    try {//from   w  w w . j a v  a  2 s.  co  m
        URL dest = new URL("http://mouflon.csc.ncsu.edu/cgi-bin/upload.cgi");
        connection = (HttpURLConnection) dest.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setChunkedStreamingMode(0);
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(twoHyphens + boundary + lineEnding);
        //Log.i("uploadFile", fileToUpload.getName());
        out.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
                + fileToUpload.getName() + "\"" + lineEnding);
        out.writeBytes("Content-Type: application/octet-stream" + lineEnding);
        out.writeBytes("Content-Transfer-Encoding: base64" + lineEnding);
        out.writeBytes(lineEnding);
        encodeFileBase64(fileToUpload, out); //TODO this works fine for small files but for some file size between 256k and 2M it begins failing.

        out.writeBytes(lineEnding);
        out.writeBytes(twoHyphens + boundary + twoHyphens + lineEnding);
        //Log.i("UploadTest", "File uploaded");
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    }
    try {
        BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
        byte[] resp = new byte[80];
        int read = 0;
        if ((read = in.read(resp)) > 0) {
            String responseString = new String(resp, 0, read);
            //Log.i("uploadFile", responseString);
            if (!responseString.equals(fileToUpload.getName())) {
                //Log.e("Upload", "File upload failed");
            }
        }
        //else 
        //Log.e("Upload", "No response received from server");

    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    }
    return success;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

private static Response invoke(UrlBuilder url, String method, String contentType,
        Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset,
        BigInteger length, Map<String, String> params) {
    try {//  w  ww . ja va 2 s  . co m
        // Log.d("URL", url.toString());

        // connect
        HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null || forceOutput);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT);

        // set content type
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        // set other headers
        if (httpHeaders != null) {
            for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                if (header.getValue() != null) {
                    for (String value : header.getValue()) {
                        conn.addRequestProperty(header.getKey(), value);
                    }
                }
            }
        }

        // range
        BigInteger tmpOffset = offset;
        if ((tmpOffset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((tmpOffset == null) || (tmpOffset.signum() == -1)) {
                tmpOffset = BigInteger.ZERO;
            }

            sb.append(tmpOffset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // add url form parameters
        if (params != null) {
            DataOutputStream ostream = null;
            OutputStream os = null;
            try {
                os = conn.getOutputStream();
                ostream = new DataOutputStream(os);

                Set<String> parameters = params.keySet();
                StringBuffer buf = new StringBuffer();

                int paramCount = 0;
                for (String it : parameters) {
                    String parameterName = it;
                    String parameterValue = (String) params.get(parameterName);

                    if (parameterValue != null) {
                        parameterValue = URLEncoder.encode(parameterValue, "UTF-8");
                        if (paramCount > 0) {
                            buf.append("&");
                        }
                        buf.append(parameterName);
                        buf.append("=");
                        buf.append(parameterValue);
                        ++paramCount;
                    }
                }
                ostream.writeBytes(buf.toString());
            } finally {
                if (ostream != null) {
                    ostream.flush();
                    ostream.close();
                }
                IOUtils.closeStream(os);
            }
        }

        // send data

        if (writer != null) {
            // conn.setChunkedStreamingMode((64 * 1024) - 1);
            OutputStream connOut = null;
            connOut = conn.getOutputStream();
            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.orange.labs.sdk.RestUtils.java

public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers,
        final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress,
        final OrangeListener.Error failure) {

    // open a URL connection to the Server
    FileInputStream fileInputStream = null;
    try {//from w  w  w  .j a  v a 2 s  . com
        fileInputStream = new FileInputStream(file);

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpsURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Don't use a Cached Copy
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");

        //
        // Define headers
        //

        // Create an unique boundary
        String boundary = "UploadBoundary";

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key.toString(), headers.get(key));
        }

        //
        // Write body part
        //
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        int bytesAvailable = fileInputStream.available();

        String marker = "\r\n--" + boundary + "\r\n";

        dos.writeBytes(marker);
        dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");

        // Create JSonObject :
        JSONObject params = new JSONObject();
        params.put("name", file.getName());
        params.put("size", String.valueOf(bytesAvailable));
        params.put("folder", folderIdentifier);

        dos.writeBytes(params.toString());

        dos.writeBytes(marker);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");

        int progressValue = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            dos.write(buf, 0, bytesRead);
            dos.flush();
            progressValue += bytesRead;
            // update progress bar
            progress.onProgress((float) progressValue / bytesAvailable);
        }

        dos.writeBytes(marker);

        //
        // Responses from the server (code and message)
        //
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        if (serverResponseCode == 200 || serverResponseCode == 201) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Response: " + line);
                response += line;
            }
            rd.close();
            JSONObject object = new JSONObject(response);
            success.onResponse(object);
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Error: " + line);
                response += line;
            }
            rd.close();
            JSONObject errorResponse = new JSONObject(response);
            failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.webkey.Ipc.java

public void comBinAuth(String turl, String postData) {
    readAuthKey();// ww w  .  ja  v  a  2 s  .c o m
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        port = prefs.getString("port", "80");
        Socket s = new Socket("127.0.0.1", Integer.parseInt(port));

        //outgoing stream redirect to socket
        DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
        byte[] utf = postData.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n"
                + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n");
        dataOutputStream.write(utf, 0, utf.length);
        dataOutputStream.flush();
        dataOutputStream.close();
        s.close();
    } catch (IOException e1) {
        //e1.printStackTrace();      
    }
    /*
    //         Log.d(TAG,"post data");
    String target = "http://127.0.0.1:"+port+"/"+authKey+turl;
    //Log.d(TAG,target);
    URL url = new URL(target);
    URLConnection conn = url.openConnection();
    // Set connection parameters.
    conn.setDoInput (true);
    conn.setDoOutput (true);
    conn.setUseCaches (false);
    //Make server believe we are form data...
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    DataOutputStream out = new DataOutputStream (conn.getOutputStream ());
    // Write out the bytes of the content string to the stream.
    out.writeBytes(postData);
    out.flush ();
    out.close ();
    // Read response
    BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ()));
    String temp;
    String response = null;
    while ((temp = in.readLine()) != null){
    response += temp + "\n";
    }
    temp = null;
    in.close ();
    System.out.println("Server response:\n'" + response + "'");
    }catch(Exception e){
    Log.d(TAG,e.toString());
    }
            
    */
}

From source file:hudson.plugins.clearcase.cleartool.CTLauncher.java

/**
 * Run a clearcase command without output to the console, the result of the
 * command is returned as a String// w w  w. j av a 2  s .  c om
 * 
 * @param cmd
 *            the command to launch using the clear tool executable
 * @param filePath
 *            optional, the path where the command should be launched
 * @return the result of the command
 * @throws IOException
 * @throws InterruptedException
 */
public String run(ArgumentListBuilder args, FilePath filePath)
        throws IOException, InterruptedException, ClearToolError {
    FilePath path = filePath;
    if (path == null) {
        path = this.nodeRoot;
    }
    ArgumentListBuilder cmd = new ArgumentListBuilder(this.executable);
    cmd.add(args.toCommandArray());

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    DataOutputStream logStream;

    if (logFile == null) {
        logStream = new DataOutputStream(new NullOutputStream());
    } else {
        logStream = new DataOutputStream(new FileOutputStream(logFile, true /*append*/));
    }

    ForkOutputStream forkStream = new ForkOutputStream(outStream, logStream);

    int code;
    String cleartoolResult;

    try {
        logStream.writeBytes(">>> " + cmd.toStringWithQuote() + "\n");

        ProcStarter starter = launcher.launch();
        starter.cmds(cmd);
        starter.envs(this.env);
        starter.stdout(forkStream);
        starter.pwd(path);

        code = launcher.launch(starter).join();

        cleartoolResult = outStream.toString();
        logStream.writeBytes("\n\n"); // to separate the commands
    } finally {
        forkStream.close();
    }

    if (code != 0 || cleartoolResult.contains("cleartool: Error")) {
        throw new ClearToolError(cmd.toStringWithQuote(), cleartoolResult, code, path);
    }

    return cleartoolResult;
}

From source file:com.kyne.webby.rtk.web.WebServer.java

public void printJSONObject(final JSONObject data, final Socket clientSocket) {
    try {//from  w w  w  . j ava  2s.  co  m
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: application/json; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        out.writeBytes(data.toJSONString());
        out.flush();
        out.close();
    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:com.wavemaker.runtime.service.WaveMakerService.java

public String remoteRESTCall(String remoteURL, String params, String method, String contentType) {
    proxyCheck(remoteURL);// ww  w.  ja  va  2 s  .c o m
    String charset = "UTF-8";
    StringBuffer returnString = new StringBuffer();
    try {
        if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null
                || params.equals("")) {
        } else {
            if (remoteURL.indexOf("?") != -1) {
                remoteURL += "&" + params;
            } else {
                remoteURL += "?" + params;
            }
        }

        URL url = new URL(remoteURL);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Opening URL: " + url);
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setRequestProperty("Accept-Charset", "application/json");
        connection.setRequestProperty("Accept-Encoding", "text/plain");
        connection.setRequestProperty("Content-Language", charset);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Transfer-Encoding", "identity");
        connection.setUseCaches(false);

        HttpServletRequest request = RuntimeAccess.getInstance().getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(name);
            if (headers != null && !name.toLowerCase().equals("accept-encoding")
                    && !name.toLowerCase().equals("accept-charset")
                    && !name.toLowerCase().equals("content-type")) {
                while (headers.hasMoreElements()) {
                    String headerValue = headers.nextElement();
                    connection.setRequestProperty(name, headerValue);
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("HEADER: " + name + ": " + headerValue);
                    }
                }
            }
        }

        // Re-wrap single quotes into double quotes
        String finalParams;
        if (contentType.toLowerCase().equals("application/json")) {
            finalParams = params.replace("\'", "\"");
            if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null
                    && !method.equals("")) {
                URLEncoder.encode(finalParams, charset);
            }
        } else {
            finalParams = params;
        }

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

        // set payload
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null
                || method.equals("")) {
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.writeBytes(finalParams);
            writer.flush();
            writer.close();
        }

        InputStream response = connection.getInputStream();
        BufferedReader reader = null;
        int responseLen = 0;
        try {
            int i = 0;
            String field;
            HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse();
            while ((field = connection.getHeaderField(i)) != null) {
                String key = connection.getHeaderFieldKey(i);
                if (key == null || field == null) {
                } else {
                    if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("transfer-encoding")
                            && field.toLowerCase().equals("chunked")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("content-length")) {
                        // do NOT use this length as return header value
                        responseLen = new Integer(field);
                    } else {
                        wmResponse.addHeader(key, field);
                    }
                }
                i++;
            }
            reader = new BufferedReader(new InputStreamReader(response, charset));
            for (String line; (line = reader.readLine()) != null;) {
                returnString.append(line);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        connection.disconnect();
        return returnString.toString();
    } catch (Exception e) {
        logger.error("ERROR in XHR proxy call: " + e.getMessage());
        throw new WMRuntimeException(e);
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Print the given String as plain text// ww w. ja v  a2  s  . c  o m
 * @param text the text to print
 * @param clientSocket the client-side socket
 */
public void printPlainText(final String text, final Socket clientSocket) {
    try {
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: text/plain; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        out.writeBytes(text);
        out.flush();
        out.close();

    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

@SuppressWarnings("unchecked")
public void printJSON(final Map<String, Object> data, final Socket clientSocket) {
    try {//from w  w  w.  j av  a2  s .  c o  m
        final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        out.writeBytes("HTTP/1.1 200 OK\r\n");
        out.writeBytes("Content-Type: application/json; charset=utf-8\r\n");
        out.writeBytes("Cache-Control: no-cache \r\n");
        out.writeBytes("Server: Bukkit Webby\r\n");
        out.writeBytes("Connection: Close\r\n\r\n");
        final JSONObject json = new JSONObject();
        json.putAll(data);
        out.writeBytes(json.toJSONString());
        out.flush();
        out.close();
    } catch (final SocketException e) {
        /* .. */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}