Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

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

Prototype

public synchronized void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to the underlying output stream.

Usage

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

public int uploadFile(String sourceFileUri, String fileName) {

    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/file-transfer/file_upload.php";

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }//from  w  w  w . j  a  v  a 2  s  .com
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
        // connection to
        // the URL
        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("uploaded_file", sourceFileUri);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + multimediaMsg
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of
        // maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);

        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

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

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path//  w w  w . jav  a  2  s.  c  o  m
 * @param httpMethod a request method (GET/POST/PUT/DELETE)
 * @param data request contents/parameters
 * @param multipart use multipart/form-data to encode the contents
 * @throws ECHOException
 */
public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart)
        throws ECHOException {
    final String secureDomain = ECHO.secureDomain;
    if (secureDomain == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    String baseUrl = new StringBuilder("https://").append(secureDomain).toString();
    String url = new StringBuilder(baseUrl).append("/").append(path).toString();

    HttpsURLConnection httpClient = null;

    try {
        URL urlObj = new URL(url);

        StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/");

        // Append the QueryString contained in path
        boolean isContainQuery = urlObj.getQuery() != null;
        if (isContainQuery)
            apiUrl.append("?").append(urlObj.getQuery());

        // Append the QueryString from data
        if (httpMethod.equals("GET") && data != null) {
            boolean firstItem = true;
            Iterator<?> iter = data.keys();
            while (iter.hasNext()) {
                if (firstItem && !isContainQuery) {
                    firstItem = false;
                    apiUrl.append("?");
                } else {
                    apiUrl.append("&");
                }
                String key = (String) iter.next();
                String value = data.optString(key);
                apiUrl.append(key);
                apiUrl.append("=");
                apiUrl.append(value);
            }
        }

        URL urlConn = new URL(apiUrl.toString());
        httpClient = (HttpsURLConnection) urlConn.openConnection();
    } catch (IOException e) {
        throw new ECHOException(e);
    }

    final String appId = ECHO.appId;
    final String appKey = ECHO.appKey;
    final String accessToken = ECHO.accessToken;

    if (appId == null || appKey == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    InputStream responseInputStream = null;

    try {
        httpClient.setRequestMethod(httpMethod);
        httpClient.addRequestProperty("X-ECHO-APP-ID", appId);
        httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey);

        // Set access token
        if (accessToken != null && !accessToken.isEmpty())
            httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken);

        // Build content
        if (!httpMethod.equals("GET") && data != null) {

            httpClient.setDoOutput(true);
            httpClient.setChunkedStreamingMode(0); // use default chunk size

            if (multipart == false) { // application/json

                httpClient.addRequestProperty("CONTENT-TYPE", "application/json");
                BufferedWriter wrBuffer = new BufferedWriter(
                        new OutputStreamWriter(httpClient.getOutputStream()));
                wrBuffer.write(data.toString());
                wrBuffer.close();

            } else { // multipart/form-data

                final String boundary = "*****" + UUID.randomUUID().toString() + "*****";
                final String twoHyphens = "--";
                final String lineEnd = "\r\n";
                final int maxBufferSize = 1024 * 1024 * 3;

                httpClient.setRequestMethod("POST");
                httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary);

                final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream());

                try {

                    JSONObject postData = new JSONObject();
                    postData.putOpt("method", httpMethod);
                    postData.putOpt("data", data);

                    new Object() {

                        public void post(JSONObject data, List<String> currentKeys)
                                throws JSONException, IOException {

                            Iterator<?> keys = data.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                List<String> newKeys = new ArrayList<String>(currentKeys);
                                newKeys.add(key);

                                Object val = data.get(key);

                                // convert JSONArray into JSONObject
                                if (val instanceof JSONArray) {
                                    JSONArray array = (JSONArray) val;
                                    JSONObject val2 = new JSONObject();

                                    for (Integer i = 0; i < array.length(); i++) {
                                        val2.putOpt(i.toString(), array.get(i));
                                    }

                                    val = val2;
                                }

                                // build form-data name
                                String name = "";
                                for (int i = 0; i < newKeys.size(); i++) {
                                    String key2 = newKeys.get(i);
                                    name += (i == 0) ? key2 : "[" + key2 + "]";
                                }

                                if (val instanceof ECHOFile) {

                                    ECHOFile file = (ECHOFile) val;
                                    if (file.getLocalBytes() == null)
                                        continue;

                                    InputStream fileInputStream = new ByteArrayInputStream(
                                            file.getLocalBytes());

                                    if (fileInputStream != null) {

                                        String mimeType = URLConnection
                                                .guessContentTypeFromName(file.getFileName());

                                        // write header
                                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name
                                                + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);
                                        outputStream.writeBytes("Content-Type: " + mimeType + lineEnd);
                                        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
                                        outputStream.writeBytes(lineEnd);

                                        // write content
                                        int bytesAvailable, bufferSize, bytesRead;
                                        do {
                                            bytesAvailable = fileInputStream.available();
                                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                            byte[] buffer = new byte[bufferSize];
                                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                            if (bytesRead <= 0)
                                                break;
                                            outputStream.write(buffer, 0, bufferSize);
                                        } while (true);

                                        fileInputStream.close();
                                        outputStream.writeBytes(lineEnd);
                                    }

                                } else if (val instanceof JSONObject) {

                                    this.post((JSONObject) val, newKeys);

                                } else {

                                    String data2 = null;
                                    try { // in case of boolean
                                        boolean bool = data.getBoolean(key);
                                        data2 = bool ? "true" : "";
                                    } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false".
                                        data2 = val.toString().trim();
                                    }

                                    // write header
                                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                    outputStream.writeBytes(
                                            "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                                    outputStream
                                            .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                                    outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd);
                                    outputStream.writeBytes(lineEnd);

                                    // write content
                                    byte[] bytes = data2.getBytes();
                                    for (int i = 0; i < bytes.length; i++) {
                                        outputStream.writeByte(bytes[i]);
                                    }

                                    outputStream.writeBytes(lineEnd);
                                }

                            }
                        }
                    }.post(postData, new ArrayList<String>());

                } catch (JSONException e) {

                    throw new ECHOException(e);

                } finally {

                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.flush();
                    outputStream.close();

                }
            }

        } else {

            httpClient.addRequestProperty("CONTENT-TYPE", "application/json");

        }

        if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) {
            responseInputStream = httpClient.getInputStream();
        }

    } catch (IOException e) {

        // get http response code
        int errorCode = -1;

        try {
            errorCode = httpClient.getResponseCode();
        } catch (IOException e1) {
            throw new ECHOException(e1);
        }

        // get error contents
        JSONObject responseObj;
        try {
            String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream());
            responseObj = new JSONObject(jsonStr);
        } catch (JSONException e1) {
            if (errorCode == 404) {
                throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found.");
            }

            throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format.");
        }

        //
        if (responseObj != null) {
            int code = responseObj.optInt("error_code");
            String message = responseObj.optString("error_message");

            if (code != 0 || !message.equals("")) {
                JSONObject details = responseObj.optJSONObject("error_details");
                if (details == null) {
                    throw new ECHOException(code, message);
                } else {
                    throw new ECHOException(code, message, details);
                }
            }
        }

        throw new ECHOException(e);

    }

    return responseInputStream;
}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. /*from ww w.  j av  a 2  s. c om*/
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

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

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:ffx.crystal.CCP4MapWriter.java

/**
 * write data to file, does not normalize
 *
 * @param data map data to write out//from w w  w. jav  a2 s .c o m
 * @param norm should the data be normalized by mean/sd?
 */
public void write(double data[], boolean norm) {
    ByteOrder b = ByteOrder.nativeOrder();
    FileOutputStream fos;
    DataOutputStream dos;

    double min = Double.POSITIVE_INFINITY;
    double max = Double.NEGATIVE_INFINITY;
    double mean = 0.0;
    double sd = 0.0;

    int n = 0;
    for (int k = 0; k < extz; k++) {
        for (int j = 0; j < exty; j++) {
            for (int i = 0; i < extx; i++) {
                int index = stride * (i + extx * (j + exty * k));
                // int index = k * (exty * (extx + 2)) + j * (extx + 2) + i;
                n++;
                if (data[index] < min) {
                    min = data[index];
                }
                if (data[index] > max) {
                    max = data[index];
                }
                mean += (data[index] - mean) / n;
            }
        }
    }

    n = 0;
    for (int k = 0; k < extz; k++) {
        for (int j = 0; j < exty; j++) {
            for (int i = 0; i < extx; i++) {
                int index = stride * (i + extx * (j + exty * k));
                // int index = k * (exty * (extx + 2)) + j * (extx + 2) + i;
                sd += pow(data[index] - mean, 2.0);
                n++;
            }
        }
    }
    sd = sqrt(sd / n);

    if (norm) {
        for (int k = 0; k < extz; k++) {
            for (int j = 0; j < exty; j++) {
                for (int i = 0; i < extx; i++) {
                    int index = stride * (i + extx * (j + exty * k));
                    data[index] = (data[index] - mean) / sd;
                }
            }
        }
        // recurse
        write(data, false);
    }

    try {
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("\nwriting CCP4 map file: \"%s\"\n", filename));
            sb.append(String.format("map min: %g max: %g mean: %g standard dev.: %g", min, max, mean, sd));
            logger.info(sb.toString());
        }

        fos = new FileOutputStream(filename);
        dos = new DataOutputStream(fos);

        byte bytes[] = new byte[2048];
        int offset = 0;

        int imapdata;
        float fmapdata;
        String mapstr;

        // header
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        bb.order(b).putInt(extx);
        bb.order(b).putInt(exty);
        bb.order(b).putInt(extz);

        // mode (2 = reals, only one we accept)
        bb.order(b).putInt(2);

        bb.order(b).putInt(orix);
        bb.order(b).putInt(oriy);
        bb.order(b).putInt(oriz);
        bb.order(b).putInt(nx);
        bb.order(b).putInt(ny);
        bb.order(b).putInt(nz);

        bb.order(b).putFloat((float) crystal.a);
        bb.order(b).putFloat((float) crystal.b);
        bb.order(b).putFloat((float) crystal.c);
        bb.order(b).putFloat((float) crystal.alpha);
        bb.order(b).putFloat((float) crystal.beta);
        bb.order(b).putFloat((float) crystal.gamma);

        bb.order(b).putInt(1);
        bb.order(b).putInt(2);
        bb.order(b).putInt(3);

        bb.order(b).putFloat((float) min);
        bb.order(b).putFloat((float) max);
        bb.order(b).putFloat((float) mean);

        bb.order(b).putInt(crystal.spaceGroup.number);
        // bb.order(b).putInt(1);

        // symmetry bytes - should set this up at some point
        // imapdata = swap ? ByteSwap.swap(320) : 320;
        bb.order(b).putInt(80);

        bb.order(b).putInt(0);

        for (int i = 0; i < 12; i++) {
            bb.order(b).putFloat(0.0f);
        }

        for (int i = 0; i < 15; i++) {
            bb.order(b).putInt(0);
        }
        dos.write(bytes, offset, 208);
        bb.rewind();

        mapstr = "MAP ";
        dos.writeBytes(mapstr);

        // machine code: double, float, int, uchar
        // 0x4441 for LE, 0x1111 for BE
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            imapdata = 0x4441;
        } else {
            imapdata = 0x1111;
        }
        bb.order(b).putInt(imapdata);

        bb.order(b).putFloat((float) sd);

        bb.order(b).putInt(1);
        dos.write(bytes, offset, 12);

        StringBuilder sb = new StringBuilder();
        sb.append("map data from ffx");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dos.writeBytes(sb.toString());

        sb = new StringBuilder();
        while (sb.length() < 80) {
            sb.append(" ");
        }
        for (int i = 0; i < 9; i++) {
            dos.writeBytes(sb.toString());
        }

        sb = new StringBuilder();
        sb.append("x,y,z");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dos.writeBytes(sb.toString());

        bb.rewind();
        for (int k = 0; k < extz; k++) {
            for (int j = 0; j < exty; j++) {
                for (int i = 0; i < extx; i++) {
                    int index = stride * (i + extx * (j + exty * k));
                    // int index = k * (exty * (extx + 2)) + j * (extx + 2) + i;
                    fmapdata = (float) data[index];
                    bb.order(b).putFloat(fmapdata);
                    if (!bb.hasRemaining()) {
                        dos.write(bytes);
                        bb.rewind();
                    }
                }
            }
        }
        if (bb.position() > 0) {
            dos.write(bytes);
            bb.rewind();
        }

        dos.close();
    } catch (Exception e) {
        String message = "Fatal exception evaluating structure factors.\n";
        logger.log(Level.SEVERE, message, e);
        System.exit(-1);
    }
}

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

private static void addUploadDataContent(List<UploadFile> uploadFiles, DataOutputStream dataOutputStream
// , String tagString
) {/*from  w  w w . j  av a  2s . co  m*/
    if (uploadFiles == null || uploadFiles.size() == 0) {
        return;
    }
    for (UploadFile uploadFile : uploadFiles) {
        // StringBuilder fileEntity = new StringBuilder();
        // fileEntity.append("--");
        // fileEntity.append(BOUNDARY);
        // fileEntity.append("\r\n");
        // fileEntity.append("Content-Disposition: form-data;name=\""
        // + uploadFile.getParameterName() + "\";filename=\""
        // + uploadFile.getFilname() + "\"\r\n");
        // fileEntity.append("Content-Type: " + uploadFile.getContentType()
        // + "\r\n\r\n");
        // outStream.write(fileEntity.toString().getBytes());

        // sb.append(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY
        // + UploadConstant.LINEEND);
        // sb.append("Content-Disposition: form-data; name=\""
        // + param.getKey() + "\"" + UploadConstant.LINEEND);
        // sb.append(UploadConstant.LINEEND);
        // sb.append(param.getValue() + UploadConstant.LINEEND);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY + UploadConstant.LINEEND);
        stringBuilder.append("Content-Disposition: form-data;")
                // + tagString
                .append("name=\"" + uploadFile.getName() + "\";")
                // + tagString
                .append("filename=\"" + FileUtil.getFileRealName(uploadFile.getFilePath())
                // uploadFile.getFilePath()
                // .substring(
                // uploadFile.getFilePath()
                // .lastIndexOf("/") + 1,
                // uploadFile.getFilePath().length())
                        + "\";")
                .append(UploadConstant.LINEEND).append("Content-Type:\"" + uploadFile.getContentType() + "\"")
                .append(UploadConstant.LINEEND).append(UploadConstant.LINEEND);
        // + tagString
        // + "ContentType=\""
        // + uploadFile.getFilePath().substring(
        // uploadFile.getFilePath().lastIndexOf(".") + 1,
        // uploadFile.getFilePath().length()) + "\";"
        // + UploadConstant.LINEEND)
        // // + tagString
        // // + "Content-Type:\""
        // // + uploadFile.getFilePath().substring(
        // // uploadFile.getFilePath().lastIndexOf(".") + 1,
        // // uploadFile.getFilePath().length()) + "\";"
        // + "Content-Type:\"image/jpg\"" + UploadConstant.LINEEND);
        // stringBuilder.append(UploadConstant.LINEEND);
        // stringBuilder.append(UploadConstant.LINEEND).append(
        // UploadConstant.LINEEND);
        // LogUtil.systemOut(stringBuilder.toString());
        FileInputStream fileInputStream = null;
        try {
            dataOutputStream.writeBytes(stringBuilder.toString());
            fileInputStream = new FileInputStream(uploadFile.getFilePath());
            // fileInputStream.available();
            // ??
            byte[] buffer = new byte[102400]; // 8k
            int count = 0;
            while ((count = fileInputStream.read(buffer)) != -1) {
                // LogUtil.systemOut("count:" + count);
                dataOutputStream.write(buffer, 0, count);
            }
            dataOutputStream.writeBytes(UploadConstant.LINEEND);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel uploadFile(String filePath, String userName) {
    SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String nowDataStr = dataFormat.format(new Date());
    String para = android.os.Build.MODEL + "_" + userName + "_" + nowDataStr + ".data";
    // String para = "LG P970" + "_" + userName + "_" + nowDataStr +
    // ".data";//w  w  w. j  av  a2s .  com
    para = URLEncoder.encode(para);
    para = para.replaceAll("\\+", "%20");
    String strUrl = UPLOAD_FILE_SERVER_CGI + "?filename=" + para;
    String result = "";
    try {
        InputStream is = new FileInputStream(filePath);
        String strLength = is.available() + "";
        URL url = new URL(strUrl);
        //            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection conn = MyHttps.getHttpURLConnection(url);
        conn.setReadTimeout(10 * 1000);
        conn.setConnectTimeout(10 * 1000);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Coentent_Length", strLength);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        // StringBuffer sb = new StringBuffer();
        // sb.append("p=");
        // dos.write(sb.toString().getBytes());
        byte[] bytes = new byte[10240];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            // String xmlString = URLEncoder.encode(Base64.encode(bytes, 0,
            // len));
            // byte[] sendData = xmlString.getBytes("UTF-8");
            // dos.write(sendData, 0, sendData.length);
            dos.write(bytes, 0, len);
        }
        is.close();
        dos.flush();
        dos.close();
        /**
         * ??? 200=? ?????
         */
        int res = conn.getResponseCode();
        if (res == 200) {
            InputStream input = conn.getInputStream();
            StringBuffer sb1 = new StringBuffer();
            int ss;
            while ((ss = input.read()) != -1) {
                sb1.append((char) ss);
            }
            result = sb1.toString();
        } else {
            return new ResultModel(Device.TRANSACTION_NET_FAIL);
        }
        return new ResultModel(new String(result));

    } catch (MalformedURLException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (KeyManagementException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }
}