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:com.dao.ShopThread.java

private void pay(String payurl) {
    LogUtil.debugPrintf("----------->");
    try {//from  www  .  jav a 2  s.  c  o  m
        String postParams = getPayDynamicParams(payurl);
        HttpsURLConnection loginConn = getHttpSConn(payurl, "POST", Integer.toString(postParams.length()));
        if (null != this.cookies) {
            loginConn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
        }

        LogUtil.debugPrintf("HEADER===" + loginConn.getRequestProperties());
        DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        int responseCode = loginConn.getResponseCode();
        LogUtil.debugPrintf("\nSending 'POST' request to URL : " + payurl);
        LogUtil.debugPrintf("Post parameters :" + postParams);
        LogUtil.debugPrintf("Response Code : " + responseCode);
        Map<String, List<String>> header = loginConn.getHeaderFields();
        LogUtil.debugPrintf("conn.getHeaderFields():" + header);
        BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer(2000);
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String payresponse = response.toString();
        LogUtil.debugPrintf("payresponse:" + payresponse);
        List<String> cookie = header.get("Set-Cookie");
        String loginInfo;
        if (responseCode != 302) {
            LogUtil.debugPrintf("----------->");
            loginInfo = "";
        } else {
            LogUtil.debugPrintf("?----------->");
            if (null != cookie && cookie.size() > 0) {
                LogUtil.debugPrintf("cookie====" + cookie);
                setCookies(cookie);
            }
            loginInfo = "?";
        }
        LogUtil.webPrintf(loginInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.caboclo.clients.OneDriveClient.java

@Override
public void putFile(File file, String path) throws IOException {
    final String BOUNDARY_STRING = "3i2ndDfv2rThIsIsPrOjEcTSYNceEMCPROTOTYPEfj3q2f";

    //We use the directory name (without actual file name) to get folder ID
    int indDirName = path.replace("/", "\\").lastIndexOf("\\");
    String targetFolderId = getFolderID(path.substring(0, indDirName));
    System.out.printf("Put file: %s\tId: %s\n", path, targetFolderId);

    if (targetFolderId == null || targetFolderId.isEmpty()) {
        return;/*from   w  w  w . j  a  v a  2  s  . c  o  m*/
    }

    URL connectURL = new URL("https://apis.live.net/v5.0/" + targetFolderId + "/files?"
            + "state=MyNewFileState&redirect_uri=https://login.live.com/oauth20_desktop.srf" + "&access_token="
            + accessToken);
    HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY_STRING);
    // set read & write
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();
    // set body
    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes("--" + BOUNDARY_STRING + "\r\n");
    dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
            + URLEncoder.encode(file.getName(), "UTF-8") + "\"\r\n");
    dos.writeBytes("Content-Type: application/octet-stream\r\n");
    dos.writeBytes("\r\n");

    FileInputStream fileInputStream = new FileInputStream(file);
    int fileSize = fileInputStream.available();
    int maxBufferSize = 8 * 1024;
    int bufferSize = Math.min(fileSize, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    // send file
    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    while (bytesRead > 0) {

        // Upload file part(s)
        dos.write(buffer, 0, bytesRead);

        int bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, buffer.length);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    fileInputStream.close();
    // send file end

    dos.writeBytes("\r\n");
    dos.writeBytes("--" + BOUNDARY_STRING + "--\r\n");

    dos.flush();

    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = null;
    StringBuilder sbuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sbuilder.append(line);
    }

    String fileId = null;
    try {
        JSONObject json = new JSONObject(sbuilder.toString());
        fileId = json.getString("id");
        //System.out.println("File ID is: " + fileId);
        //System.out.println("File name is: " + json.getString("name"));
        //System.out.println("File uploaded sucessfully.");
    } catch (JSONException e) {
        Logger.getLogger(OneDriveClient.class.getName()).log(Level.WARNING,
                "Error uploading file " + file.getName(), e);
    }
}

From source file:com.norconex.committer.idol.IdolCommitter.java

/**
 * Add/Remove/Commit documents based on the parameters passed to the method.
 * @param url URL to post//from ww  w  .jav a 2 s  .  c o  m
 * @param the content to post
 */
private void postToIDOL(String url, String content) {
    HttpURLConnection con = null;
    DataOutputStream wr = null;
    try {
        con = createURLConnection(url);
        wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(content);
        wr.flush();

        //Get the response
        int responseCode = con.getResponseCode();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending 'POST' request to URL : " + url);
            LOG.debug("Post parameters : " + content);
            LOG.debug("Server Response Code : " + responseCode);
        }
        String response = IOUtils.toString(con.getInputStream());
        if ((isCFS() && !StringUtils.contains(response, "SUCCESS"))
                || (!isCFS() && !StringUtils.contains(response, "INDEXID"))) {
            throw new CommitterException("Unexpected HTTP response: " + response);
        }
        wr.close();
    } catch (IOException e) {
        throw new CommitterException("Cannot post content to " + createURL(), e);
    } finally {
        if (con != null) {
            con.disconnect();
        }
        IOUtils.closeQuietly(wr);
    }
}

From source file:org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable.java

/**
 * Render the words via TSNE/*from w ww .  j  a  v  a2s  . c o  m*/
 *
 * @param tsne           the tsne to use
 * @param numWords
 * @param connectionInfo
 */
@Override
public void plotVocab(BarnesHutTsne tsne, int numWords, UiConnectionInfo connectionInfo) {
    try {
        final List<String> labels = fitTnseAndGetLabels(tsne, numWords);
        final INDArray reducedData = tsne.getData();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < reducedData.rows() && i < numWords; i++) {
            String word = labels.get(i);
            INDArray wordVector = reducedData.getRow(i);
            for (int j = 0; j < wordVector.length(); j++) {
                sb.append(String.valueOf(wordVector.getDouble(j))).append(",");
            }
            sb.append(word);
        }

        String address = connectionInfo.getFirstPart() + "/tsne/post/" + connectionInfo.getSessionId();
        //            System.out.println("ADDRESS: " + address);
        URI uri = new URI(address);

        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        //            connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Type", "multipart/form-data");
        connection.setDoOutput(true);

        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
        dos.writeBytes(sb.toString());
        dos.flush();
        dos.close();

        try {
            int responseCode = connection.getResponseCode();
            System.out.println("RESPONSE CODE: " + responseCode);

            if (responseCode != 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

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

                log.warn("Error posting to remote UI - received response code {}\tContent: {}", response,
                        response.toString());
            }
        } catch (IOException e) {
            log.warn("Error posting to remote UI at {}", uri, e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.pdx.cecs.orcycle.UserInfoUploader.java

boolean uploadUserInfoV4() {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {//w  ww .j a v  a2 s. c o  m
        JSONArray userResponses = getUserResponsesJSON();

        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonUser;
        if (null != (jsonUser = getUserJSON())) {
            try {
                String deviceId = userId;

                dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n");
                dos.writeBytes(
                        fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n");
                dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(fieldSep + ContentField("userResponses") + userResponses.toString() + "\r\n");
                dos.writeBytes(fieldSep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                // TODO: Record somehow that data was uploaded successfully
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:org.opentox.toxotis.client.http.PostHttpClient.java

/**
 * According to the the configuration of the PostHttpClient, performs a remote POST
 * request to the server identified by the URI provided in the constructor. First,
 * the protected method {@link PostHttpClient#initializeConnection(java.net.URI)
 * initializeConnection(URI)} is invoked and then a DataOutputStream opens to
 * transfer the data to the server.//  ww  w  .  jav  a2  s.  c  o m
 *
 * @throws ServiceInvocationException
 *      Encapsulates an IOException which might be thrown due to I/O errors
 *      during the data transaction.
 */
@Override
public void post() throws ServiceInvocationException {
    String query = getParametersAsQuery();
    if ((fileContentToPost != null || inputStream != null) && query != null && !query.isEmpty()) {
        postMultiPart();
    } else {
        connect(getUri().toURI());
        DataOutputStream wr;
        try {
            getPostLock().lock(); // LOCK
            wr = new DataOutputStream(getConnection().getOutputStream());

            if (query != null && !query.isEmpty()) {
                wr.writeBytes(getParametersAsQuery());// POST the parameters
            } else if (model != null) {
                model.write(wr);
            } else if (staxComponent != null) {
                staxComponent.writeRdf(wr);
            } else if (stringToPost != null) {
                wr.writeChars(stringToPost);
            } else if (bytesToPost != null) {
                wr.writeBytes(bytesToPost);
            } else if (fileContentToPost != null || inputStream != null) {
                // Post from file (binary data) or from other input stream
                InputStream is = null;
                InputStreamReader isr = null;
                BufferedReader br = null;
                boolean doCloseInputStream = false;
                // choose input stream (used-defined or from file)
                if (fileContentToPost != null) {
                    is = new FileInputStream(fileContentToPost);
                    doCloseInputStream = true;
                } else {
                    is = inputStream;
                }
                try {
                    isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);
                    String line;
                    while ((line = br.readLine()) != null) {
                        wr.writeBytes(line);
                        wr.writeChars("\n");
                    }
                } catch (IOException ex) {
                    throw new ConnectionException("Unable to post data to the remote service at '" + getUri()
                            + "' - The connection dropped " + "unexpectidly while POSTing.", ex);
                } finally {
                    Throwable thr = null;
                    if (br != null) {
                        try {
                            br.close();
                        } catch (final IOException ex) {
                            thr = ex;
                        }
                    }
                    if (isr != null) {
                        try {
                            isr.close();
                        } catch (final IOException ex) {
                            thr = ex;
                        }
                    }
                    if (doCloseInputStream) {
                        try {
                            is.close();
                        } catch (final IOException ex) {
                            thr = ex;
                        }
                    }
                    if (thr != null) {
                        ConnectionException connExc = new ConnectionException("Stream could not close", thr);
                        connExc.setActor(getUri() != null ? getUri().toString() : "N/A");
                        //TODO Why is the exception not thrown here?
                    }
                }
            }
            wr.flush();
            wr.close();
        } catch (final IOException ex) {
            ConnectionException postException = new ConnectionException(
                    "Exception caught while posting the parameters to the " + "remote web service located at '"
                            + getUri() + "'",
                    ex);
            postException.setActor(getUri() != null ? getUri().toString() : "N/A");
            throw postException;
        } finally {
            getPostLock().unlock(); // UNLOCK
        }
    }
}

From source file:com.QuarkLabs.BTCeClient.exchangeApi.AuthRequest.java

/**
 * Makes any request, which require authentication
 *
 * @param method    Method of Trade API/*  www .  j a  v  a 2s  . c  om*/
 * @param arguments Additional arguments, which can exist for this method
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(@NotNull String method, Map<String, String> arguments) throws JSONException {

    if (key.length() == 0 || secret.length() == 0) {
        return new JSONObject("{success:0,error:'No key/secret provided'}");
    }

    if (arguments == null) {
        arguments = new HashMap<>();
    }

    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    DataOutputStream wr = null;
    try {
        connection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Key", key);
        byte[] array = mac.doFinal(postData.getBytes("UTF-8"));
        connection.setRequestProperty("Sign", byteArrayToHexString(array));
        wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(response));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.pinterest.deployservice.events.EventSenderImpl.java

public void sendDeployEvent(String what, String tags, String data) throws Exception {
    JsonObject object = new JsonObject();
    object.addProperty("what", what);
    object.addProperty("tags", tags);
    object.addProperty("data", data);
    final String paramsToSend = object.toString();
    DataOutputStream output = null;
    HttpURLConnection connection = null;
    int retry = 0;
    while (retry < TOTAL_RETRY) {
        try {/*w w  w .  j  a va2s.c o m*/
            URL requestUrl = new URL(this.URL);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setDoOutput(true);

            connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setRequestMethod("POST");
            output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(paramsToSend);
            output.flush();
            output.close();
            String result = IOUtils.toString(connection.getInputStream(), "UTF-8").toLowerCase();
            LOG.info("Successfully send events to the statsboard: " + result);
            return;
        } catch (Exception e) {
            LOG.error("Failed to send event", e);
        } finally {
            IOUtils.closeQuietly(output);
            if (connection != null) {
                connection.disconnect();
            }
            retry++;
        }
    }
    throw new DeployInternalException("Failed to send event");
}

From source file:eu.eexcess.partnerwizard.webservice.WizardRESTService.java

public String cmdExecute(ArrayList<String> commands) {
    Process shell = null;/*from   www  . j a  v  a2s.  co  m*/
    DataOutputStream out = null;
    BufferedReader in = null;
    StringBuilder processOutput = new StringBuilder();
    processOutput.append(new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()))
            .append("\n");
    try {
        shell = Runtime.getRuntime().exec("cmd");//su if needed
        out = new DataOutputStream(shell.getOutputStream());

        in = new BufferedReader(new InputStreamReader(shell.getInputStream()));

        // Executing commands
        for (String command : commands) {
            LOGGER.info("executing:\n" + command);
            out.writeBytes(command + "\n");
            out.flush();
        }

        out.writeBytes("exit\n");
        out.flush();
        String line;
        while ((line = in.readLine()) != null) {
            processOutput.append(line).append("\n");
        }

        //LOGGER.info("result:\n" + processOutput);
        processOutput.append(new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()))
                .append("\n");
        String output = processOutput.toString();
        shell.waitFor();
        LOGGER.info(processOutput.toString());
        LOGGER.info("finished!");
        return output;
    } catch (Exception e) {
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
            // shell.destroy();
        } catch (Exception e) {
            // hopeless
        }
    }
    return "";
}

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;/* w  w  w  .j a v a 2  s  .  c o  m*/
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}