Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:com.reddit.util.ApiUtil.java

/**
 * Experimental right now.  I messed around with this but never really used it for anything.
 * /*from w w  w.j a v a2 s . com*/
 * @param url should be new URL("https://ssl.reddit.com/api/login/myusername");
 * @param user
 * @param pw
 * @throws IOException
 * @throws JSONException
 */
public void login(URL url, String user, String pw) throws IOException, JSONException {

    String data = "api_type=json&user=" + user + "&passwd=" + pw;
    HttpURLConnection httpUrlConn = null;
    httpUrlConn = (HttpURLConnection) url.openConnection();
    httpUrlConn.setRequestMethod("POST");
    httpUrlConn.setDoOutput(true);
    httpUrlConn.setUseCaches(false);
    httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpUrlConn.setRequestProperty("Content-Length", String.valueOf(data.length()));

    DataOutputStream dataOutputStream = new DataOutputStream(httpUrlConn.getOutputStream());
    dataOutputStream.writeBytes(data);
    dataOutputStream.flush();
    dataOutputStream.close();
    InputStream is = httpUrlConn.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    for (Entry<String, List<String>> r : httpUrlConn.getHeaderFields().entrySet()) {
        System.out.println(r.getKey() + ": " + r.getValue());
    }
    bufferedReader.close();
    System.out.println("Response: " + response.toString());
    this.setModHash(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("modhash"));
    this.setCookie(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("cookie"));

}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processPostRequest(URL url, byte[] data, String contentType, String keyStore,
        String keyStorePassword) throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;//  w w w .j a  v a2s  .  c om
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.addRequestProperty("x-ms-version", "2014-04-01");
    con.setRequestProperty("Content-Length", String.valueOf(data.length));
    con.setRequestProperty("Content-Type", contentType);

    DataOutputStream requestStream = new DataOutputStream(con.getOutputStream());
    requestStream.write(data);
    requestStream.flush();
    requestStream.close();

    return con.getResponseCode();
}

From source file:api.APICall.java

public String executePost(String targetURL, String urlParameters) {
    URL url;/* w w  w  .  ja  v a 2 s.  c  o  m*/
    HttpURLConnection connection = null;
    try {
        // Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        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();
        return response.toString();

    } catch (SocketException se) {
        se.printStackTrace();
        System.out.println("Server is down.");
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.trsst.client.MultiPartRequestEntity.java

public void writeRequest(OutputStream arg0) throws IOException {
    DataOutputStream out = new DataOutputStream(arg0);
    out.writeBytes("--" + boundary + "\r\n");
    writeEntry(base, out);//from  w  ww .j  a  va 2  s.co  m
    out.writeBytes("--" + boundary + "\r\n");
    if (content != null) {
        for (int i = 0; i < content.length; i++) {
            writeContent(content[i], contentId[i], contentType[i], out);
            out.writeBytes("\r\n" + "--" + boundary + "--");
        }
    }
    out.flush();
}

From source file:net.servicestack.client.JsonServiceClient.java

public HttpURLConnection createRequest(String requestUrl, String httpMethod, byte[] requestBody,
        String requestType) {/*from w w w  . j  a v a2s .co m*/
    try {
        URL url = new URL(requestUrl);

        HttpURLConnection req = (HttpURLConnection) url.openConnection();
        req.setDoOutput(true);

        if (timeoutMs != null) {
            req.setConnectTimeout(timeoutMs);
            req.setReadTimeout(timeoutMs);
        }

        req.setRequestMethod(httpMethod);
        req.setRequestProperty(HttpHeaders.Accept, MimeTypes.Json);

        if (requestType != null) {
            req.setRequestProperty(HttpHeaders.ContentType, requestType);
        }

        if (requestBody != null) {
            req.setRequestProperty(HttpHeaders.ContentLength, Integer.toString(requestBody.length));
            DataOutputStream wr = new DataOutputStream(req.getOutputStream());
            wr.write(requestBody);
            wr.flush();
            wr.close();
        }

        if (RequestFilter != null) {
            RequestFilter.exec(req);
        }

        if (GlobalRequestFilter != null) {
            GlobalRequestFilter.exec(req);
        }

        return req;

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java

private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents) {
    HttpURLConnection conn = null;
    String fileId = null;//w ww.  jav a2  s .c  o m

    String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId
            + "?uploadType=media";

    try {

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(fileUpdateUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length));

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(fileContents);
        wr.flush();
        wr.close();

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        Utilities.LogDebug("File updated : " + fileId);

    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;

}

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report.//from  ww  w.ja  v a 2s  . co  m
 *
 * @param context         the application context
 * @param withDevicesLogs true to include the device logs
 * @param withCrashLogs   true to include the crash logs
 */
private static void sendBugReport(final Context context, final boolean withDevicesLogs,
        final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) {
    new AsyncTask<Void, Integer, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report");

            if (bugReportFile.exists()) {
                bugReportFile.delete();
            }

            String serverError = null;
            FileWriter fileWriter = null;

            try {
                fileWriter = new FileWriter(bugReportFile);
                JsonWriter jsonWriter = new JsonWriter(fileWriter);
                jsonWriter.beginObject();

                // android bug report
                jsonWriter.name("user_agent").value("Android");

                // logs list
                jsonWriter.name("logs");
                jsonWriter.beginArray();

                // the logs are optional
                if (withDevicesLogs) {
                    List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>());
                    for (File f : files) {
                        if (!mIsCancelled) {
                            jsonWriter.beginObject();
                            jsonWriter.name("lines").value(convertStreamToString(f));
                            jsonWriter.endObject();
                            jsonWriter.flush();
                        }
                    }
                }

                if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) {
                    jsonWriter.beginObject();
                    jsonWriter.name("lines").value(getLogCatError());
                    jsonWriter.endObject();
                    jsonWriter.flush();
                }

                jsonWriter.endArray();

                jsonWriter.name("text").value(bugDescription);

                String version = "";

                if (null != Matrix.getInstance(context).getDefaultSession()) {
                    version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n";
                }

                version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " "
                        + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n";
                version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n";
                version += "SDK version:  " + Matrix.getInstance(context).getDefaultSession().getVersion(true)
                        + "\n";
                version += "Olm version:  "
                        + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true)
                        + "\n";

                jsonWriter.name("version").value(version);

                jsonWriter.endObject();
                jsonWriter.close();

            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage());
                serverError = e.getLocalizedMessage();
            } catch (OutOfMemoryError oom) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage());
                serverError = oom.getMessage();

                if (TextUtils.isEmpty(serverError)) {
                    serverError = "Out of memory";
                }
            }

            try {
                if (null != fileWriter) {
                    fileWriter.close();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage());
            }

            if (TextUtils.isEmpty(serverError) && !mIsCancelled) {

                // the screenshot is defined here
                // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg");
                InputStream inputStream = null;
                HttpURLConnection conn = null;
                try {
                    inputStream = new FileInputStream(bugReportFile);
                    final int dataLen = inputStream.available();

                    // should never happen
                    if (0 == dataLen) {
                        return "No data";
                    }

                    URL url = new URL(context.getResources().getString(R.string.bug_report_url));
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Content-Length", Integer.toString(dataLen));
                    // avoid caching data before really sending them.
                    conn.setFixedLengthStreamingMode(inputStream.available());

                    conn.connect();

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

                    byte[] buffer = new byte[8192];

                    // read file and write it into form...
                    int bytesRead;
                    int totalWritten = 0;

                    while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
                        dos.write(buffer, 0, bytesRead);
                        totalWritten += bytesRead;
                        publishProgress(totalWritten * 100 / dataLen);
                    }

                    dos.flush();
                    dos.close();

                    int mResponseCode;

                    try {
                        // Read the SERVER RESPONSE
                        mResponseCode = conn.getResponseCode();
                    } catch (EOFException eofEx) {
                        mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
                    }

                    // if the upload failed, try to retrieve the reason
                    if (mResponseCode != HttpURLConnection.HTTP_OK) {
                        serverError = null;
                        InputStream is = conn.getErrorStream();

                        if (null != is) {
                            int ch;
                            StringBuilder b = new StringBuilder();
                            while ((ch = is.read()) != -1) {
                                b.append((char) ch);
                            }
                            serverError = b.toString();
                            is.close();

                            // check if the error message
                            try {
                                JSONObject responseJSON = new JSONObject(serverError);
                                serverError = responseJSON.getString("error");
                            } catch (JSONException e) {
                                Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage());
                            }

                            // should never happen
                            if (null == serverError) {
                                serverError = "Failed with error " + mResponseCode;
                            }

                            is.close();
                        }
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG,
                            "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage());
                    serverError = e.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Failed to upload";
                    }
                } catch (OutOfMemoryError oom) {
                    Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage());
                    serverError = oom.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Out ouf memory";
                    }

                } finally {
                    try {
                        if (null != conn) {
                            conn.disconnect();
                        }
                    } catch (Exception e2) {
                        Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage());
                    }
                }

                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage());
                    }
                }
            }
            return serverError;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            if (null != listener) {
                try {
                    listener.onProgress((null == progress) ? 0 : progress[0]);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage());
                }
            }
        }

        @Override
        protected void onPostExecute(String reason) {
            if (null != listener) {
                try {
                    if (mIsCancelled) {
                        listener.onUploadCancelled();
                    } else if (null == reason) {
                        listener.onUploadSucceed();
                    } else {
                        listener.onUploadFailed(reason);
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage());
                }
            }
        }
    }.execute();
}

From source file:org.scigap.iucig.controller.ScienceDisciplineController.java

@ResponseBody
@RequestMapping(value = "/updateScienceDiscipline", method = RequestMethod.POST)
public void updateScienceDiscipline(@RequestBody ScienceDiscipline discipline, HttpServletRequest request)
        throws Exception {
    try {/*w  ww  . ja  va 2 s .c  o m*/
        String remoteUser;
        if (request != null) {
            remoteUser = request.getRemoteUser();
        } else {
            throw new Exception("Remote user is null");
        }
        int primarySubDisId = 0;
        int secondarySubDisId = 0;
        int tertiarySubDisId = 0;
        String urlParameters = "user=" + remoteUser;
        if (discipline != null) {
            Map<String, String> primarySubDisc = discipline.getPrimarySubDisc();
            if (primarySubDisc != null && !primarySubDisc.isEmpty()) {
                for (String key : primarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        primarySubDisId = Integer.valueOf(primarySubDisc.get(key));
                        urlParameters += "&discipline1=" + primarySubDisId;
                    }
                }
            } else {
                Map<String, Object> primaryDiscipline = discipline.getPrimaryDisc();
                if (primaryDiscipline != null && !primaryDiscipline.isEmpty()) {
                    Object subdisciplines = primaryDiscipline.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    primarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline1=" + primarySubDisId;
                    }
                }
            }
            Map<String, String> secondarySubDisc = discipline.getSecondarySubDisc();
            if (secondarySubDisc != null && !secondarySubDisc.isEmpty()) {
                for (String key : secondarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        secondarySubDisId = Integer.valueOf(secondarySubDisc.get(key));
                        urlParameters += "&discipline2=" + secondarySubDisId;
                    }
                }
            } else {
                Map<String, Object> secondaryDisc = discipline.getSecondaryDisc();
                if (secondaryDisc != null && !secondaryDisc.isEmpty()) {
                    Object subdisciplines = secondaryDisc.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    secondarySubDisId = Integer
                                            .valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline2=" + secondarySubDisId;
                    }
                }
            }

            Map<String, String> tertiarySubDisc = discipline.getTertiarySubDisc();
            if (tertiarySubDisc != null && !tertiarySubDisc.isEmpty()) {
                for (String key : tertiarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        tertiarySubDisId = Integer.valueOf(tertiarySubDisc.get(key));
                        urlParameters += "&discipline3=" + tertiarySubDisId;
                    }
                }
            } else {
                Map<String, Object> tertiaryDisc = discipline.getTertiaryDisc();
                if (tertiaryDisc != null && !tertiaryDisc.isEmpty()) {
                    Object subdisciplines = tertiaryDisc.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    tertiarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline3=" + tertiarySubDisId;
                    }
                }
            }
            URL obj = new URL(SCIENCE_DISCIPLINE_URL + "discipline/");
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            urlParameters += "&date=" + discipline.getDate() + "&source=cybergateway&commit=Update&cluster="
                    + discipline.getCluster();
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + SCIENCE_DISCIPLINE_URL);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

protected void configConnection(HttpURLConnection connection) throws IOException {
    connection.setConnectTimeout(mConnectTimeout);
    connection.setReadTimeout(mReadTimeout);
    connection.setUseCaches(false);// w ww.  j  a va  2  s . c  o m
    connection.setDoInput(true);
    connection.setRequestProperty("Charset", Charset.defaultCharset().name());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent", mUserAgent);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Cookie", CookieHelper.parse(mRequestParams.getCookies()));

    switch (mType) {
    case TYPE_TEXT: {
        connection.setRequestMethod(mMethod.name());
        if (mMethod == Method.POST) {
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", CONTENT_TYPE_TEXT);
            String paramsString;
            if (!TextUtils.isEmpty(mRequestParams.getString())) {
                paramsString = mRequestParams.getString();
            } else {
                paramsString = parseMapToUrlParamsString(mRequestParams.getArrayMap());
            }
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsString.getBytes());
            outputStream.flush();
            outputStream.close();
        }
        break;
    }
    case TYPE_BITMAP: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }
        outputStream.write(builder.toString().getBytes());

        outputStream.writeBytes(PREFIX + BOUNDARY + LINE_END);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "bitmap" + "\";filename=\""
                + "bitmap.jpg" + "\"" + LINE_END);
        outputStream.writeBytes(LINE_END);
        outputStream.write(bitmapToBytes(mBitmap));
        outputStream.writeBytes(LINE_END);
        outputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
        outputStream.flush();
        outputStream.close();
        break;
    }
    case TYPE_FILE: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }

        for (ArrayMap.Entry<String, File> entry : mFileMap.entrySet()) {
            String text = PREFIX + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"; filename=\"" + entry.getValue().getName() + "\"" + LINE_END
                    + "Content-Type:" + "application/octet-stream" + LINE_END
                    + "Content-Transfer-Encoding: binary" + LINE_END + LINE_END;
            outputStream.writeBytes(builder.append(text).toString());

            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(entry.getValue()));
            int length;
            byte[] bytes = new byte[1024 * 1024];
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            inputStream.close();
        }

        String endTag = LINE_END + PREFIX + BOUNDARY + PREFIX + LINE_END;
        outputStream.writeBytes(endTag);
        outputStream.flush();
        outputStream.close();
        break;
    }
    }
}

From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java

private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) {

    String fileId = null;//from   w w w  .  j  a  v  a  2  s  .  c o  m
    HttpURLConnection conn = null;

    String createFileUrl = "https://www.googleapis.com/drive/v2/files";

    String createFilePayload = "   {\n" + "             \"title\": \"" + fileName + "\",\n"
            + "             \"mimeType\": \"" + mimeType + "\",\n" + "             \"parents\": [\n"
            + "              {\n" + "               \"id\": \"" + parentFolderId + "\"\n" + "              }\n"
            + "             ]\n" + "            }";

    try {

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            //Due to a pre-froyo bug
            //http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            System.setProperty("http.keepAlive", "false");
        }

        URL url = new URL(createFileUrl);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "GPSLogger for Android");
        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/json");

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

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(createFilePayload);
        wr.flush();
        wr.close();

        fileId = null;

        String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream());

        JSONObject fileMetadataJson = new JSONObject(fileMetadata);
        fileId = fileMetadataJson.getString("id");
        Utilities.LogDebug("File created with ID " + fileId);

    } catch (Exception e) {

        System.out.println(e.getMessage());
        System.out.println(e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

    }

    return fileId;
}