Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runFileUpload() throws IOException {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594";
    Log.i("Andfrnd/TwAjax", "URL=" + getURL());
    URL url = new URL(getURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);//from w ww.  ja  v  a  2  s.  com
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        connection.setRequestProperty("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--");

    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    for (NameValuePair nvp : myPostData) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
    }
    for (PostFile pf : myPostFiles) {
        pf.writeToStream(outputStream, boundary);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    myHttpStatus = connection.getResponseCode();

    outputStream.flush();
    outputStream.close();

    if (myHttpStatus < 400) {
        myResult = convertStreamToString(connection.getInputStream());
    } else {
        myResult = convertStreamToString(connection.getErrorStream());
    }

    success = true;
}

From source file:com.google.glassware.NotifyServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Respond with OK and status 200 in a timely fashion to prevent redelivery
    response.setContentType("text/html");
    Writer writer = response.getWriter();
    writer.append("OK");
    writer.close();//from   w w w . ja  v a  2 s. c o m

    // Get the notification object from the request body (into a string so we
    // can log it)
    BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String notificationString = "";

    String responseStringForFaceDetection = null;
    // Count the lines as a very basic way to prevent Denial of Service attacks
    int lines = 0;
    String line;
    while ((line = notificationReader.readLine()) != null) {
        notificationString += line;
        lines++;

        // No notification would ever be this long. Something is very wrong.
        if (lines > 1000) {
            throw new IOException("Attempted to parse notification payload that was unexpectedly long.");
        }
    }
    notificationReader.close();

    LOG.info("got raw notification " + notificationString);

    JsonFactory jsonFactory = new JacksonFactory();

    // If logging the payload is not as important, use
    // jacksonFactory.fromInputStream instead.
    Notification notification = jsonFactory.fromString(notificationString, Notification.class);

    LOG.info("Got a notification with ID: " + notification.getItemId());

    // Figure out the impacted user and get their credentials for API calls
    String userId = notification.getUserToken();
    Credential credential = AuthUtil.getCredential(userId);
    Mirror mirrorClient = MirrorClient.getMirror(credential);

    if (notification.getCollection().equals("locations")) {
        LOG.info("Notification of updated location");
        Mirror glass = MirrorClient.getMirror(credential);
        // item id is usually 'latest'
        Location location = glass.locations().get(notification.getItemId()).execute();

        LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude());
        MirrorClient.insertTimelineItem(credential, new TimelineItem()
                .setText("Java Quick Start says you are now at " + location.getLatitude() + " by "
                        + location.getLongitude())
                .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location)
                .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE"))));

        // This is a location notification. Ping the device with a timeline item
        // telling them where they are.
    } else if (notification.getCollection().equals("timeline")) {
        // Get the impacted timeline item
        TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute();
        LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId());

        // If it was a share, and contains a photo, update the photo's caption to
        // acknowledge that we got it.
        if (notification.getUserActions().contains(new UserAction().setType("SHARE"))
                && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) {
            String finalresponseForCard = null;

            String questionString = timelineItem.getText();
            if (!questionString.isEmpty()) {
                String[] questionStringArray = questionString.split(" ");

                LOG.info(timelineItem.getText() + " is the questions asked by the user");
                LOG.info("A picture was taken");

                if (questionString.toLowerCase().contains("search")
                        || questionString.toLowerCase().contains("tag")
                        || questionString.toLowerCase().contains("train")
                        || questionString.toLowerCase().contains("mark")
                        || questionString.toLowerCase().contains("recognize")
                        || questionString.toLowerCase().contains("what is")) {

                    //Fetching the image from the timeline
                    InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(),
                            timelineItem.getAttachments().get(0));

                    //converting the image to Base64
                    Base64 base64Object = new Base64(false);
                    String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray()
                    // byteArrayForOutputStream.close();
                    encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1");

                    //sending the API request
                    LOG.info("Sending request to API");
                    //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call
                    try {
                        String urlParameters = "";
                        String tag = "";

                        if (questionString.toLowerCase().contains("tag")
                                || questionString.toLowerCase().contains("mark")) {

                            tag = extractTagFromQuestion(questionString);
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag="
                                    + tag + "&base64=" + encodedImageToBase64;

                        } else if (questionString.toLowerCase().contains("train")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1";
                        } else if (questionString.toLowerCase().contains("search")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        } else if (questionString.toLowerCase().contains("recognize")
                                || questionString.toLowerCase().contains("what is")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        }
                        byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
                        int postDataLength = postData.length;
                        String newrequest = "http://rekognition.com/func/api/";
                        URL url = new URL(newrequest);
                        HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection();

                        // Increase the timeout for reading the response
                        connectionFaceDetection.setReadTimeout(15000);

                        connectionFaceDetection.setDoOutput(true);
                        connectionFaceDetection.setDoInput(true);
                        connectionFaceDetection.setInstanceFollowRedirects(false);
                        connectionFaceDetection.setRequestMethod("POST");
                        connectionFaceDetection.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
                        connectionFaceDetection.setRequestProperty("X-Mashape-Key",
                                "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp");
                        connectionFaceDetection.setRequestProperty("charset", "utf-8");
                        connectionFaceDetection.setRequestProperty("Accept", "application/json");
                        connectionFaceDetection.setRequestProperty("Content-Length",
                                Integer.toString(postDataLength));
                        connectionFaceDetection.setUseCaches(false);

                        DataOutputStream outputStreamForFaceDetection = new DataOutputStream(
                                connectionFaceDetection.getOutputStream());
                        outputStreamForFaceDetection.write(postData);

                        BufferedReader inputStreamForFaceDetection = new BufferedReader(
                                new InputStreamReader((connectionFaceDetection.getInputStream())));

                        StringBuilder responseForFaceDetection = new StringBuilder();

                        while ((responseStringForFaceDetection = inputStreamForFaceDetection
                                .readLine()) != null) {
                            responseForFaceDetection.append(responseStringForFaceDetection);
                        }

                        //closing all the connections
                        inputStreamForFaceDetection.close();
                        outputStreamForFaceDetection.close();
                        connectionFaceDetection.disconnect();

                        responseStringForFaceDetection = responseForFaceDetection.toString();
                        LOG.info(responseStringForFaceDetection);

                        JSONObject responseJSONObjectForFaceDetection = new JSONObject(
                                responseStringForFaceDetection);
                        if (questionString.toLowerCase().contains("train") || questionString.contains("tag")
                                || questionString.toLowerCase().contains("mark")) {
                            JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection
                                    .getJSONObject("usage");
                            finalresponseForCard = usageKeyFromResponse.getString("status");
                            if (!tag.equals(""))
                                finalresponseForCard = "Object is tagged as " + tag;
                        } else {
                            JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection
                                    .getJSONObject("scene_understanding");
                            JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches");
                            JSONObject firstResultFromArray = matchesArray.getJSONObject(0);

                            double percentSureOfObject;
                            //If an score has value 1, then the value type is Integer else the value type is double
                            if (firstResultFromArray.get("score") instanceof Integer) {
                                percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100;
                            } else
                                percentSureOfObject = (Double) firstResultFromArray.get("score") * 100;

                            finalresponseForCard = "The object is " + firstResultFromArray.getString("tag")
                                    + ". Match score is" + percentSureOfObject;
                        }

                        //section where if it doesn't contain anything about tag or train

                    } catch (Exception e) {
                        LOG.warning(e.getMessage());
                    }

                }

                else
                    finalresponseForCard = "Could not understand your words";
            } else
                finalresponseForCard = "Could not understand your words";

            TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem();

            responseCardForSDKAlchemyAPI.setText(finalresponseForCard);
            responseCardForSDKAlchemyAPI
                    .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD")));
            responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard);
            responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows");
            responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT"));
            mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute();
            LOG.info("New card added to the timeline");

        } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) {
            LOG.info("It was a note taken with the 'take a note' voice command. Processing it.");

            // Grab the spoken text from the timeline card and update the card with
            // an HTML response (deleting the text as well).
            String noteText = timelineItem.getText();
            String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)];

            timelineItem.setText(null);
            timelineItem.setHtml(makeHtmlForCard(
                    "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>"));
            timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE")));

            mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute();
        } else {
            LOG.warning("I don't know what to do with this notification, so I'm ignoring it.");
        }
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataWithID(String requestUrl, String requestMethod, String requestBody, int uuid,
        String successCallback, String errorCallback) {
    try {// w w w  .  j a va2 s .c  o  m
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.writeBytes("&uuid=" + uuid);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            //callbackContext.success(responseBody);
            String js = "javascript:" + successCallback + "(" + uuid + ", '" + responseBody + "');";
            injectJS(js);
        } else {
            //callbackContext.error("Fail to get the response, response code: " + responseCode + ", response message: " + responseMessage);
            String js = "javascript:" + errorCallback + "(" + uuid + ", '" + "Fail to get the response" + "');";
            injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataWithID(String requestUrl, String requestMethod, String requestBody, int uuid,
        CallbackContext callbackContext) {
    try {// ww  w . j  a  va 2  s . c  o  m
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

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

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.writeBytes("&uuid=" + uuid);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(uuid + ", " + responseBody);
            //String js = "javascript:" + successCallback + "(" + uuid + ", '" + responseBody + "');";
            //injectJS(js);
        } else {
            callbackContext.error(uuid + ", Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
            //String js = "javascript:" + errorCallback + "(" + uuid + ", '" + "Fail to get the response" + "');";
            //injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

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 {//from w w  w.ja  va  2 s. c om
        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:edu.ku.brc.specify.tools.FormDisplayer.java

/**
 * //from   ww  w.  j a v  a 2  s  . c  om
 */
private File checkForTemplateFiles(final String dstDirPath) {
    String templatePath = dstDirPath + File.separator + "schema_template.html";

    File templateFile = new File(templatePath); //$NON-NLS-1$
    if (templateFile.exists()) {
        return templateFile;
    }

    System.out.println(templatePath);
    try {
        File dstDirFile = new File(dstDirPath);
        if (!dstDirFile.exists()) {
            if (!dstDirFile.mkdirs()) {
                JOptionPane.showMessageDialog(null, "Error creating the site directory.");
            }
        }

        String zipFilePath = dstDirPath + File.separator + "site.zip";
        System.out.println("[" + zipFilePath + "]");

        String url = "http://files.specifysoftware.org/site.zip";
        HTTPGetter getter = new HTTPGetter();
        InputStream ins = getter.beginHTTPRequest(url);
        //DataInputStream  dins   = new DataInputStream(ins);
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(zipFilePath));
        byte[] bytes = new byte[4096];

        int totalBytes = 0;
        /*while (dins.available() > 0)
        {
        int len = dins.read(bytes);
        dos.write(bytes, 0, len);
        totalBytes += len;
        System.out.println(len+" / "+totalBytes);
        }*/
        int numBytes = 0;
        do {
            numBytes = ins.read(bytes);
            if (numBytes > 0) {
                dos.write(bytes, 0, numBytes);
                totalBytes += numBytes;
                System.out.println(numBytes);
            }

        } while (numBytes > 0);

        dos.flush();
        dos.close();
        //dins.close();

        System.out.println(totalBytes);

        File zipFile = new File(zipFilePath);
        System.out.println("zipFile: " + zipFile + " exists: " + zipFile.exists());

        List<File> unzippedFiles = ZipFileHelper.getInstance().unzipToFiles(zipFile);
        for (File unzippedFile : unzippedFiles) {
            FileUtils.copyFileToDirectory(unzippedFile, dstDirFile);
        }

        if (templateFile.exists()) {
            return templateFile;
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "You are missing the template that is needed to run this tool.");
    }
    return null;
}

From source file:com.wsc.myexample.decisionForest.MyTestForest.java

private void testFile(String inPath, String outPath, DataConverter converter, MyDecisionForest forest,
        Dataset dataset, /*List<double[]> results,*/ Random rng, ResultAnalyzer analyzer) throws IOException {
    // create the predictions file
    DataOutputStream ofile = null;

    if (outPath != null) {
        ofile = new DataOutputStream(new FileOutputStream(outPath));
    }/*from ww  w  .  j a va  2 s .  c o  m*/

    DataInputStream input = new DataInputStream(new FileInputStream(inPath));
    try {
        Scanner scanner = new Scanner(input);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.isEmpty()) {
                continue; // skip empty lines
            }

            Instance instance = converter.convert(line);
            if (instance == null)
                continue;

            double prediction = forest.classify(dataset, rng, instance);

            if (ofile != null) {
                ofile.writeChars(Double.toString(prediction)); // write the prediction
                ofile.writeChar('\n');
            }

            //        results.add(new double[] {dataset.getLabel(instance), prediction});

            analyzer.addInstance(dataset.getLabelString(dataset.getLabel(instance)),
                    new ClassifierResult(dataset.getLabelString(prediction), 1.0));
        }

        scanner.close();
    } finally {
        Closeables.closeQuietly(input);
        ofile.close();
    }
}

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/* 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:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void appendToFile(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    if (!isNull(ArgList) && !isUndefined(ArgList)) {
        try {/*from   w  ww .  j a  va 2 s  .  com*/
            FileOutputStream file = new FileOutputStream((String) ArgList[0], true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes((String) ArgList[1]);
            out.flush();
            out.close();
        } catch (Exception er) {
            throw new RuntimeException(er.toString());
        }
    } else {
        throw new RuntimeException("The function call appendToFile requires arguments.");
    }
}

From source file:net.nym.library.http.UploadImagesRequest.java

/**
 * ???/*from  w  w  w. j  av a  2  s . c om*/
 *
 * @param url
 *            Service net address
 * @param params
 *            text content
 * @param files
 *            pictures
 * @return String result of Service response
 * @throws java.io.IOException
 */
public static String postFile(String url, Map<String, Object> params, Map<String, File> files)
        throws IOException {
    String result = "";
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";

    StringBuilder sb = new StringBuilder("?");
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        //                sb.append(PREFIX);
        //                sb.append(BOUNDARY);
        //                sb.append(LINEND);
        //                sb.append("Content-Disposition: form-data; name=\""
        //                        + entry.getKey() + "\"" + LINEND);
        //                sb.append("Content-Type: text/plain; charset=" + CHARSET
        //                        + LINEND);
        //                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        //                sb.append(LINEND);
        //                sb.append(entry.getValue());
        //                sb.append(LINEND);
        //                String key = entry.getKey();
        //                sb.append("&");
        //                sb.append(key).append("=").append(params.get(key));
        //                Log.i("%s=%s",key,params.get(key).toString());
        sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString()))
                .append("&");
    }
    sb.deleteCharAt(sb.length() - 1);
    URL uri = new URL(url + sb.toString());
    HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
    conn.setConnectTimeout(50000);
    conn.setDoInput(true);// ?
    conn.setDoOutput(true);// ?
    conn.setUseCaches(false); // ??
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    // ?
    //            StringBuilder sb = new StringBuilder();
    //            for (Map.Entry<String, Object> entry : params.entrySet()) {
    ////                sb.append(PREFIX);
    ////                sb.append(BOUNDARY);
    ////                sb.append(LINEND);
    ////                sb.append("Content-Disposition: form-data; name=\""
    ////                        + entry.getKey() + "\"" + LINEND);
    ////                sb.append("Content-Type: text/plain; charset=" + CHARSET
    ////                        + LINEND);
    ////                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
    ////                sb.append(LINEND);
    ////                sb.append(entry.getValue());
    ////                sb.append(LINEND);
    //                String key = entry.getKey();
    //                sb.append("&");
    //                sb.append(key).append("=").append(params.get(key));
    //                Log.i("%s=%s",key,params.get(key).toString());
    //            }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    //            outStream.write(sb.toString().getBytes());
    // ?
    if (files != null) {
        for (Map.Entry<String, File> file : files.entrySet()) {
            StringBuilder sbFile = new StringBuilder();
            sbFile.append(PREFIX);
            sbFile.append(BOUNDARY);
            sbFile.append(LINEND);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                    + file.getValue().getName() + "\"" + LINEND);
            sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
            sbFile.append(LINEND);
            Log.i(sbFile.toString());
            outStream.write(sbFile.toString().getBytes());

            InputStream is = new FileInputStream(file.getValue());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            outStream.write(LINEND.getBytes());
        }
        // ?
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
    }

    outStream.flush();
    // ??
    int res = conn.getResponseCode();
    InputStream in = conn.getInputStream();
    StringBuilder sbResult = new StringBuilder();
    if (res == 200) {
        int ch;
        while ((ch = in.read()) != -1) {
            sbResult.append((char) ch);
        }
    }
    result = sbResult.toString();
    outStream.close();
    conn.disconnect();
    return result;
}