Example usage for org.apache.http.entity.mime.content FileBody FileBody

List of usage examples for org.apache.http.entity.mime.content FileBody FileBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content FileBody FileBody.

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:com.quwu.xinwo.release.Release_Activity.java

/**
 * ?/*from  w  w  w .  ja v  a  2 s  .  co  m*/
 * */
private String uploading2(String url, List<String> path, String goods_name, String good_description,
        String audiofile, String good_region, String city_region, String small_area, String twolevel_id,
        String three_id, String goods_price, String normal_use, String warranty_period, String no_repair,
        String brand_new, String jingdong, String mainland_licensed, String since, String user_id,
        String freight, String rentprice, String renttime, String whether_pack)
        throws ParseException, IOException {
    String result = null;
    HttpPost httpPost = new HttpPost(url);
    // httpPost.addHeader("Content-Type", "video/mpeg");
    // httpPost.addHeader("User-Agent", "imgfornote");
    // ?
    MultipartEntity reqEntity = new MultipartEntity();

    for (int i = 0; i < path.size(); i++) {// 
        File file1 = null;
        if (path.get(i).equals("drawable://" + R.drawable.fb_icn_video)
                || path.get(i).equals("drawable://" + R.drawable.fb_icn_carema)) {

        } else if (path.get(i).equals(CameraUtils.CAMERA_VIDEO)) {
            file1 = new File(path.get(i));
            // if (!file1.getAbsoluteFile().equals("")) {
            FileBody fileBody = new FileBody(file1);
            reqEntity.addPart("videofile", fileBody);
        } else {
            file1 = new File(path.get(i));
            // if (!file1.getAbsoluteFile().equals("")) {
            FileBody fileBody = new FileBody(file1);
            reqEntity.addPart("imagefile", fileBody);
            // }
        }
    }
    if (!audiofile.equals("")) {
        File file3 = new File(audiofile);// 
        if (!file3.getAbsoluteFile().equals("")) {
            FileBody fileBody = new FileBody(file3);
            reqEntity.addPart("audiofile", fileBody);
        }
    }
    StringBody type = new StringBody(goods_name);
    reqEntity.addPart("goods_name", type);
    StringBody type1 = new StringBody(good_description);
    reqEntity.addPart("good_description", type1);
    StringBody type2 = new StringBody(good_region);
    reqEntity.addPart("good_region", type2);
    StringBody type3 = new StringBody(city_region);
    reqEntity.addPart("city_region", type3);
    StringBody type4 = new StringBody(small_area);
    reqEntity.addPart("small_area", type4);
    StringBody type6 = new StringBody(twolevel_id);
    reqEntity.addPart("twolevel_id", type6);
    StringBody type19 = new StringBody(three_id);
    reqEntity.addPart("three_id", type19);
    StringBody type7 = new StringBody(goods_price);
    reqEntity.addPart("goods_price", type7);
    StringBody type8 = new StringBody(normal_use);
    reqEntity.addPart("normal_use", type8);
    StringBody type9 = new StringBody(warranty_period);
    reqEntity.addPart("warranty_period", type9);
    StringBody type10 = new StringBody(no_repair);
    reqEntity.addPart("no_repair", type10);
    StringBody type11 = new StringBody(brand_new);
    reqEntity.addPart("brand_new", type11);
    StringBody type12 = new StringBody(jingdong);
    reqEntity.addPart("jingdong", type12);
    StringBody type13 = new StringBody(mainland_licensed);
    reqEntity.addPart("mainland_licensed", type13);
    StringBody type14 = new StringBody(since);
    reqEntity.addPart("since", type14);
    StringBody type15 = new StringBody(user_id);
    reqEntity.addPart("user_id", type15);
    StringBody type16 = new StringBody(freight);
    reqEntity.addPart("freight", type16);
    StringBody type17 = new StringBody(rentprice);
    reqEntity.addPart("rentprice", type17);
    StringBody type18 = new StringBody(renttime);
    reqEntity.addPart("renttime", type18);
    StringBody type20 = new StringBody(whether_pack);
    reqEntity.addPart("whether_pack", type20);
    httpPost.setEntity(reqEntity);
    // ?HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    // ?HttpResponse
    HttpResponse httpResponse = httpclient.execute(httpPost);
    // HttpStatus.SC_OK?
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // ?
        result = EntityUtils.toString(httpResponse.getEntity());
    } else {
        pd.dismiss();
    }
    return result;
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

@Deprecated
protected HttpResponse put(URI url, File requestContent, boolean authenticate) throws Exception {
    HttpPut method = new HttpPut(url);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("param_name", new StringBody("value"));
    entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
    HttpResponse response = putOrPost(method, entity, authenticate);
    int status = response.getStatusLine().getStatusCode();
    if (status == SC_MOVED_TEMPORARILY) {
        String original = url.toString();
        url = URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
        if (!original.equals(url.toString())) {
            EntityUtils.consumeQuietly(response.getEntity());
            method = new HttpPut(url);
            entity = new MultipartEntity();
            entity.addPart("param_name", new StringBody("value"));
            entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
            response = putOrPost(method, entity, true);
        }//from ww w. j  av  a2  s .co  m
    }

    return response;
}

From source file:wsserver.EKF1TimerSessionBean.java

private boolean postMultipartSectUpd(List<CbEkfgroupUpd1csectToBx> uswps) {
    String charset = "UTF-8";
    String requestURL = systemURL + "bitrix/ekflibraries/corpbus/manipulate_data.php";
    boolean reply = true;
    String sreply = "";

    if (uswps.isEmpty())
        return reply;
    long allFileSize = 0;

    String logStr = "Upd sect cnt=" + uswps.size() + ". ";
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {//ww w. j  a  v a  2  s .  c  o m
        MultipartUtility multipart = new MultipartUtility(requestURL, charset);
        HttpPost httppost = new HttpPost(requestURL);
        MultipartEntityBuilder reqBuilder = MultipartEntityBuilder.create();

        multipart.addHeaderField("User-Agent", "CodeJava");
        httppost.addHeader("User-Agent", "CodeJava");
        multipart.addHeaderField("Test-Header", "Header-Value");
        int index = 0;
        multipart.addFormField("OTYPE", "UPDATE");
        reqBuilder.addPart("OTYPE", new StringBody("UPDATE", ContentType.TEXT_PLAIN));
        multipart.addFormField("ENTITY", "1CSECT");
        reqBuilder.addPart("ENTITY", new StringBody("1CSECT", ContentType.TEXT_PLAIN));
        int ocnt = uswps.size();
        multipart.addFormField("OCNT", "" + ocnt);
        reqBuilder.addPart("OCNT", new StringBody("" + ocnt, ContentType.TEXT_PLAIN));
        //String logStr=""; 
        for (CbEkfgroupUpd1csectToBx npwp : uswps) {
            multipart.addFormField("SID" + index, npwp.getSid());
            reqBuilder.addPart("SID" + index, new StringBody(npwp.getSid(), ContentType.TEXT_PLAIN));
            //if(!npwp.getSid().equals(npwp.getCbBxgroupId()))
            //    multipart.addFormField("SETSID"+index, "1");
            //else
            //    multipart.addFormField("SETSID"+index, "0");
            //multipart.addFormField("NEWSID"+index, npwp.getCbBxgroupId());

            logStr += "[" + index + "] NAME " + npwp.getBxname() + "," + npwp.getF1cname() + ","
                    + npwp.getBxparentId() + "," + npwp.getF1cparentId();

            if (!npwp.getBxname().equals(npwp.getF1cname())) {
                multipart.addFormField("SETSNAME" + index, "1");
                reqBuilder.addPart("SETSNAME" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSNAME" + index, "0");
                reqBuilder.addPart("SETSNAME" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            if (!npwp.getBxparentId().equals(npwp.getF1cparentId())) {
                multipart.addFormField("SETSGRXMLID" + index, "1");
                reqBuilder.addPart("SETSGRXMLID" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSGRXMLID" + index, "0");
                reqBuilder.addPart("SETSGRXMLID" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SNAME" + index, npwp.getF1cname());
            reqBuilder.addPart("SNAME" + index, new StringBody(npwp.getF1cname(), ContentType.TEXT_PLAIN));
            multipart.addFormField("SGRXMLID" + index, npwp.getF1cparentId());
            reqBuilder.addPart("SGRXMLID" + index,
                    new StringBody(npwp.getF1cparentId(), ContentType.TEXT_PLAIN));

            boolean error_file_operation = false, uploadFiles = true;
            long sectFilesSize = 0;
            boolean tooLargeDsc = false, tooLargeGb = false, tooLargeDoc = false;

            ArrayList<String> dscFiles = new ArrayList<String>();

            try {
                if (!npwp.getBxDescriptsJson().equals(npwp.getF1cDescriptsJson())) {
                    //logStr+="["+npwp.getF1cDescriptsJson()+"]";
                    JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cDescriptsJson()));
                    JsonObject jo = jsonReader.readObject();

                    int dcount = 0;
                    logStr += "cnt=" + jo.getString("dc", "0");
                    for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) {
                        logStr += ("[" + i + "]");
                        try {
                            if (jo.getString("fp" + i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/"));
                                if (f.length() <= maxPostedFileSize
                                        && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                                    dscFiles.add(jo.getString("fp" + i).replace("\\", "/"));
                                    multipart.addFormField("FDSC" + index + "DSC" + dcount,
                                            jo.getString("dsc" + i));
                                    multipart.addFormField("FDSC" + index + "FN" + dcount,
                                            jo.getString("fn" + i));
                                    reqBuilder.addPart("FDSC" + index + "DSC" + dcount,
                                            new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN));
                                    reqBuilder.addPart("FDSC" + index + "FN" + dcount,
                                            new StringBody(jo.getString("fn" + i), ContentType.TEXT_PLAIN));
                                    sectFilesSize += f.length();
                                    dcount++;
                                } else {
                                    tooLargeDsc = true;
                                    logStr += "Too large " + jo.getString("fp" + i);
                                }
                            }

                        } catch (Exception fle) {
                            //sectFilesSize=0;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dsc file operation!!! " + fle);
                        }

                    }

                    if (dcount > 0) {
                        multipart.addFormField("FDSCDC" + index, "" + dcount);
                        reqBuilder.addPart("FDSCDC" + index,
                                new StringBody("" + dcount, ContentType.TEXT_PLAIN));
                    }

                }
            } catch (Exception fle) {
                logStr += (npwp.getF1cname() + " Error F1cDescriptsJson parse operation!!! " + fle + "[["
                        + npwp.getF1cDescriptsJson() + "]]");
            }

            ArrayList<String> gbFiles = new ArrayList<String>();

            try {
                if (!npwp.getBxGabaritsJson().equals(npwp.getF1cGabaritsJson())) {
                    //logStr+="["+npwp.getF1cGabaritsJson()+"]";
                    JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cGabaritsJson()));
                    JsonObject jo = jsonReader.readObject();

                    int dcount = 0;
                    logStr += "cnt=" + jo.getString("dc", "0");
                    for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) {
                        logStr += ("[" + i + "]");
                        try {
                            if (jo.getString("fp" + i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/"));
                                if (f.length() <= maxPostedFileSize
                                        && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                                    gbFiles.add(jo.getString("fp" + i).replace("\\", "/"));
                                    multipart.addFormField("FGB" + index + "DSC" + dcount,
                                            jo.getString("dsc" + i));
                                    multipart.addFormField("FGB" + index + "FN" + dcount,
                                            jo.getString("fn" + i));
                                    reqBuilder.addPart("FGB" + index + "DSC" + dcount,
                                            new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN));
                                    reqBuilder.addPart("FGB" + index + "FN" + dcount,
                                            new StringBody(jo.getString("fn" + i), ContentType.TEXT_PLAIN));
                                    sectFilesSize += f.length();
                                    dcount++;
                                    logStr += "[=" + dcount + "=]";
                                } else {
                                    tooLargeGb = true;
                                    logStr += "Too large " + jo.getString("fp" + i);
                                }
                            }

                        } catch (Exception fle) {
                            //sectFilesSize=0;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dsc file operation!!! " + fle);
                        }

                    }

                    if (dcount > 0) {
                        multipart.addFormField("FGBDC" + index, "" + dcount);
                        reqBuilder.addPart("FGBDC" + index,
                                new StringBody("" + dcount, ContentType.TEXT_PLAIN));
                    }

                }
            } catch (Exception fle) {
                logStr += (npwp.getF1cname() + " Error F1cGabaritsJson parse operation!!! " + fle + "[["
                        + npwp.getF1cGabaritsJson() + "]]");
            }

            ArrayList<String> docFiles = new ArrayList<String>();

            try {
                if (!npwp.getBxDocsJson().equals(npwp.getF1cDocsJson())) {
                    //logStr+="["+npwp.getF1cDocsJson()+"]";
                    JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cDocsJson()));
                    JsonObject jo = jsonReader.readObject();

                    int dcount = 0;
                    logStr += "cnt=" + jo.getString("dc", "0");
                    for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) {
                        logStr += ("[" + i + "]");
                        try {
                            if (jo.getString("fp" + i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/"));
                                if (f.length() <= maxPostedDocFileSize
                                        && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                                    docFiles.add(jo.getString("fp" + i).replace("\\", "/"));
                                    multipart.addFormField("FDOC" + index + "DSC" + dcount,
                                            jo.getString("dsc" + i));
                                    //logStr+=("FDOC"+index+"FN+"+dcount+"="+jo.getString("fn"+i));
                                    multipart.addFormField("FDOC" + index + "FN" + dcount,
                                            jo.getString("fn" + i));
                                    reqBuilder.addPart("FDOC" + index + "DSC" + dcount,
                                            new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN));
                                    reqBuilder.addPart("FDOC" + index + "FN" + dcount,
                                            new StringBody(StringEscapeUtils.escapeJava(jo.getString("fn" + i)),
                                                    ContentType.TEXT_PLAIN));
                                    sectFilesSize += f.length();
                                    dcount++;
                                } else {
                                    tooLargeDoc = true;
                                    logStr += "Too large " + jo.getString("fp" + i);
                                }
                            }

                        } catch (Exception fle) {
                            //sectFilesSize=0;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error doc file operation!!! " + fle);
                        }

                    }

                    if (dcount > 0) {
                        multipart.addFormField("FDOCDC" + index, "" + dcount);
                        reqBuilder.addPart("FDOCDC" + index,
                                new StringBody("" + dcount, ContentType.TEXT_PLAIN));
                    }

                }
            } catch (Exception fle) {
                logStr += (npwp.getF1cname() + " Error F1cDocsJson parse operation!!! " + fle + "[["
                        + npwp.getF1cDocsJson() + "]]");
            }

            try {
                if (npwp.getF1cPicture().length() > 0 && npwp.getBxPicture().length() == 0 && uploadFiles) {
                    File f = new File(mountImgPath + npwp.getF1cPicture().replace("\\", "/"));
                    if (f.length() <= maxPostedFileSize
                            && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                        sectFilesSize += f.length();
                    }
                }
            } catch (Exception fle) {
                //sectFilesSize=0;
                error_file_operation = true;
                logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cPicture file operation!!! " + fle);
            }

            try {

                if (npwp.getF1cMcatalog().length() > 0 && npwp.getBxMcatalog().length() == 0 && uploadFiles) {
                    File f = new File(mountImgPath + npwp.getF1cMcatalog().replace("\\", "/"));
                    if (f.length() <= maxPostedDocFileSize
                            && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                        sectFilesSize += f.length();
                    }
                }

            } catch (Exception fle) {
                //sectFilesSize=0;
                error_file_operation = true;
                logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cMcatalog file operation!!! " + fle);
            }

            if ((allFileSize + sectFilesSize) > maxPostFilePartSize) {
                logStr += ("NAME " + npwp.getF1cname() + " - too big sect files sizes summ!!!");
                //continue; 
            } else {
                if (!error_file_operation) {
                    try {
                        if (!npwp.getF1cPicture().equals(npwp.getBxPicture()) && uploadFiles) {
                            File f = new File(mountImgPath + npwp.getF1cPicture().replace("\\", "/"));
                            if (f.length() <= maxPostedFileSize
                                    && ((allFileSize + f.length()) < maxPostFilePartSize)) {
                                logStr += ",getF1cPicture " + npwp.getF1cPicture() + "fname=" + f.getName()
                                        + ",fpath=" + f.getPath() + ",flength=[" + f.length() + "]";
                                allFileSize += f.length();

                                try {
                                    BufferedImage originalImage = ImageIO.read(f);
                                    if ((originalImage.getHeight() > 400 || originalImage.getWidth() > 400)
                                            && false) {
                                        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                                                : originalImage.getType();
                                        BufferedImage resizeImageJpg = resizeImage(originalImage, type);

                                        logStr += "Not require resize";
                                        //multipart.addFilePart("PICTURE"+index, (resizeImageJpg) );
                                        //multipart.addFormField("SETPICTURE"+index, "1");
                                    } else {
                                        logStr += "Not require resize";
                                        multipart.addFilePart("PICTURE" + index, (f));
                                        multipart.addFormField("SETPICTURE" + index, "1");
                                        multipart.addFormField("PICTURE_PATH" + index,
                                                StringEscapeUtils.escapeJava(npwp.getF1cPicture()));
                                        reqBuilder.addPart("PICTURE" + index, new FileBody(f));
                                        reqBuilder.addPart("SETPICTURE" + index,
                                                new StringBody("1", ContentType.TEXT_PLAIN));
                                    }
                                } catch (Exception frle) {
                                    logStr += "Error resizing" + frle;
                                    multipart.addFilePart("PICTURE" + index, (f));
                                    multipart.addFormField("SETPICTURE" + index, "1");
                                    multipart.addFormField("PICTURE_PATH" + index,
                                            StringEscapeUtils.escapeJava(npwp.getF1cPicture()));
                                    reqBuilder.addPart("PICTURE" + index, new FileBody(f));
                                    reqBuilder.addPart("SETPICTURE" + index,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                }
                            } else {
                                multipart.addFormField("SETPICTURE" + index, "0");
                                reqBuilder.addPart("SETPICTURE" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                                logStr += ",getF1cPicture " + f.length() + " more "
                                        + maxPostedFileSize / 1000000 + "Mbytes or too big allFileSize";
                            }
                        }
                    } catch (Exception fle) {
                        error_file_operation = true;
                        logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cPicture file operation!!! "
                                + fle);
                    }
                    try {
                        if (npwp.getF1cMcatalog().length() > 0 && npwp.getBxMcatalog().length() == 0
                                && uploadFiles) {
                            File f = new File(mountImgPath + npwp.getF1cMcatalog().replace("\\", "/"));
                            if (f.length() <= maxPostedDocFileSize
                                    && ((allFileSize + f.length()) < maxPostFilePartSize)) {
                                logStr += ",getF1cMcatalog " + npwp.getF1cMcatalog();
                                allFileSize += f.length();
                                multipart.addFilePart("MASTER_CATALOG" + index, (f));
                                multipart.addFormField("SETMASTER_CATALOG" + index, "1");
                                reqBuilder.addPart("MASTER_CATALOG" + index, new FileBody(f));
                                reqBuilder.addPart("SETMASTER_CATALOG" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETMASTER_CATALOG" + index, "0");
                                reqBuilder.addPart("SETMASTER_CATALOG" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                                logStr += ",getF1cMcatalog " + f.length() + " more "
                                        + maxPostedDocFileSize / 1000000 + "Mbytes or too big allFileSize";
                            }
                        }
                    } catch (Exception fle) {
                        error_file_operation = true;
                        logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cMcatalog file operation!!! "
                                + fle);
                    }

                    int succFilesCount = 0;
                    for (int i = 0; i < dscFiles.size(); i++) {
                        try {
                            if (dscFiles.get(i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + dscFiles.get(i));
                                long lastFSize = 0;
                                lastFSize = f.length();
                                if (lastFSize <= maxPostedFileSize
                                        && ((allFileSize + lastFSize) < maxPostFilePartSize)) {
                                    logStr += ",dscFiles " + dscFiles.get(i);
                                    multipart.addFilePart("FDSC" + index + "FP" + i, (f));
                                    multipart.addFormField("FDSC" + index + "FPSET" + i, "1");
                                    reqBuilder.addPart("FDSC" + index + "FP" + i, new FileBody(f));
                                    reqBuilder.addPart("FDSC" + index + "FPSET" + i,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                    succFilesCount++;
                                    allFileSize += lastFSize;
                                } else {
                                    //if(lastFSize>maxPostedFileSize)
                                    //    succFilesCount++;
                                    tooLargeDsc = true;
                                    multipart.addFormField("FDSC" + index + "FPSET" + i, "0");
                                    reqBuilder.addPart("FDSC" + index + "FPSET" + i,
                                            new StringBody("0", ContentType.TEXT_PLAIN));
                                    logStr += ",dscFiles " + f.length() + " more " + maxPostedFileSize / 1000000
                                            + "Mbytes or too big allFileSize";
                                }
                            }
                        } catch (Exception fle) {
                            tooLargeDsc = true;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dscFiles file operation!!! "
                                    + fle);
                        }

                    }

                    if (!tooLargeDsc) {
                        if ((dscFiles.size() <= 0)
                                || ((succFilesCount >= 1) && (succFilesCount >= (int) (dscFiles.size() / 2)))) {
                            if (!npwp.getBxDescriptsJson().equals(npwp.getF1cDescriptsJson())) {
                                multipart.addFormField("SETDESCRIPTS_JSON" + index, "1");
                                reqBuilder.addPart("SETDESCRIPTS_JSON" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETDESCRIPTS_JSON" + index, "0");
                                reqBuilder.addPart("SETDESCRIPTS_JSON" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                            }
                            multipart.addFormField("DESCRIPTS_JSON" + index,
                                    StringEscapeUtils.escapeJava(npwp.getF1cDescriptsJson()));
                            reqBuilder.addPart("DESCRIPTS_JSON" + index,
                                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cDescriptsJson()),
                                            ContentType.TEXT_PLAIN));
                        } else
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dscFiles count!!! ");
                    }

                    succFilesCount = 0;
                    for (int i = 0; i < gbFiles.size(); i++) {
                        try {
                            if (gbFiles.get(i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + gbFiles.get(i));
                                long lastFSize = 0;
                                lastFSize = f.length();
                                if (lastFSize <= maxPostedFileSize
                                        && ((allFileSize + lastFSize) < maxPostFilePartSize)) {
                                    logStr += ",gbFiles " + gbFiles.get(i);
                                    multipart.addFilePart("FGB" + index + "FP" + i, (f));
                                    multipart.addFormField("FGB" + index + "FPSET" + i, "1");
                                    reqBuilder.addPart("FGB" + index + "FP" + i, new FileBody(f));
                                    reqBuilder.addPart("FGB" + index + "FPSET" + i,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                    succFilesCount++;
                                    allFileSize += lastFSize;
                                } else {
                                    //if(lastFSize>maxPostedFileSize)
                                    //    succFilesCount++;
                                    tooLargeGb = true;
                                    multipart.addFormField("FGB" + index + "FPSET" + i, "0");
                                    reqBuilder.addPart("FGB" + index + "FPSET" + i,
                                            new StringBody("0", ContentType.TEXT_PLAIN));
                                    logStr += ",gbFiles " + f.length() + " more " + maxPostedFileSize / 1000000
                                            + "Mbytes or too big allFileSize";
                                }
                            }
                        } catch (Exception fle) {
                            tooLargeGb = true;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error gbrFiles file operation!!! "
                                    + fle);
                        }

                    }

                    if (!tooLargeGb) {
                        if ((gbFiles.size() <= 0)
                                || ((succFilesCount >= 1) && (succFilesCount >= (int) (gbFiles.size() / 2)))) {
                            if (!npwp.getBxGabaritsJson().equals(npwp.getF1cGabaritsJson())) {
                                multipart.addFormField("SETGABARITS_JSON" + index, "1");
                                reqBuilder.addPart("SETGABARITS_JSON" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETGABARITS_JSON" + index, "0");
                                reqBuilder.addPart("SETGABARITS_JSON" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                            }
                            multipart.addFormField("GABARITS_JSON" + index,
                                    StringEscapeUtils.escapeJava(npwp.getF1cGabaritsJson()));
                            reqBuilder.addPart("GABARITS_JSON" + index,
                                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cGabaritsJson()),
                                            ContentType.TEXT_PLAIN));
                        } else
                            logStr += ("NAME " + npwp.getF1cname() + " - Error gbrFiles count!!! ");
                    }

                    succFilesCount = 0;
                    for (int i = 0; i < docFiles.size(); i++) {
                        try {
                            if (docFiles.get(i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + docFiles.get(i));
                                long lastFSize = 0;
                                lastFSize = f.length();
                                if (lastFSize <= maxPostedDocFileSize
                                        && ((allFileSize + lastFSize) < maxPostFilePartSize)) {
                                    logStr += ",docFiles " + docFiles.get(i);
                                    multipart.addFilePart("FDOC" + index + "FP" + i, (f));
                                    multipart.addFormField("FDOC" + index + "FPSET" + i, "1");
                                    reqBuilder.addPart("FDOC" + index + "FP" + i, new FileBody(f));
                                    reqBuilder.addPart("FDOC" + index + "FPSET" + i,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                    succFilesCount++;
                                    allFileSize += lastFSize;
                                } else {
                                    //if(lastFSize>maxPostedFileSize)
                                    //    succFilesCount++;
                                    tooLargeDoc = true;
                                    multipart.addFormField("FDOC" + index + "FPSET" + i, "0");
                                    reqBuilder.addPart("FDOC" + index + "FPSET" + i,
                                            new StringBody("0", ContentType.TEXT_PLAIN));
                                    logStr += ",docFiles " + f.length() + " more "
                                            + maxPostedDocFileSize / 1000000 + "Mbytes or too big allFileSize";
                                }
                            }
                        } catch (Exception fle) {
                            tooLargeDoc = true;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error docFiles file operation!!! "
                                    + fle);
                        }

                    }

                    if (!tooLargeDoc) {
                        if ((docFiles.size() <= 0)
                                || ((succFilesCount >= 1) && (succFilesCount >= (int) (docFiles.size() / 2)))) {
                            if (!npwp.getBxDocsJson().equals(npwp.getF1cDocsJson())) {
                                multipart.addFormField("SETDOCS_JSON" + index, "1");
                                reqBuilder.addPart("SETDOCS_JSON" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETDOCS_JSON" + index, "0");
                                reqBuilder.addPart("SETDOCS_JSON" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                            }
                            multipart.addFormField("DOCS_JSON" + index,
                                    StringEscapeUtils.escapeJava(npwp.getF1cDocsJson()));
                            reqBuilder.addPart("DOCS_JSON" + index,
                                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cDocsJson()),
                                            ContentType.TEXT_PLAIN));
                        } else
                            logStr += ("NAME " + npwp.getF1cname() + " - Error docFiles count!!! ");
                    }

                }
            }

            if (npwp.getBxSortOrder() != npwp.getF1cSortOrder()) {
                multipart.addFormField("SETSORT_ORDER" + index, "1");
                reqBuilder.addPart("SETSORT_ORDER" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSORT_ORDER" + index, "0");
                reqBuilder.addPart("SETSORT_ORDER" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SORT_ORDER" + index, "" + npwp.getF1cSortOrder());
            reqBuilder.addPart("SORT_ORDER" + index,
                    new StringBody("" + npwp.getF1cSortOrder(), ContentType.TEXT_PLAIN));

            if (!npwp.getBxDescription().equals(npwp.getF1cDescription())) {
                multipart.addFormField("SETDESCRIPTION" + index, "1");
                reqBuilder.addPart("SETDESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETDESCRIPTION" + index, "0");
                reqBuilder.addPart("SETDESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cDescription()));
            reqBuilder.addPart("DESCRIPTION" + index,
                    new StringBody("" + npwp.getF1cSortOrder(), ContentType.TEXT_PLAIN));

            if (!npwp.getBxFullDescription().equals(npwp.getF1cFullDescription())) {
                multipart.addFormField("SETFULL_DESCRIPTION" + index, "1");
                reqBuilder.addPart("SETFULL_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETFULL_DESCRIPTION" + index, "0");
                reqBuilder.addPart("SETFULL_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("FULL_DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cFullDescription()));
            reqBuilder.addPart("FULL_DESCRIPTION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cFullDescription()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxTypeCompleting().equals(npwp.getF1cTypeCompleting())) {
                multipart.addFormField("SETTYPE_COMPLETING" + index, "1");
                reqBuilder.addPart("SETTYPE_COMPLETING" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETTYPE_COMPLETING" + index, "0");
                reqBuilder.addPart("SETTYPE_COMPLETING" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("TYPE_COMPLETING" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cTypeCompleting()));
            reqBuilder.addPart("TYPE_COMPLETING" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cTypeCompleting()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxCharGabarits().equals(npwp.getF1cCharGabarits())) {
                multipart.addFormField("SETCHAR_GABARITS" + index, "1");
                reqBuilder.addPart("SETCHAR_GABARITS" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETCHAR_GABARITS" + index, "0");
                reqBuilder.addPart("SETCHAR_GABARITS" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("CHAR_GABARITS" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cCharGabarits()));
            reqBuilder.addPart("CHAR_GABARITS" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cCharGabarits()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxShortDescription().equals(npwp.getF1cShortDescription())) {
                multipart.addFormField("SETSHORT_DESCRIPTION" + index, "1");
                reqBuilder.addPart("SETSHORT_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSHORT_DESCRIPTION" + index, "0");
                reqBuilder.addPart("SETSHORT_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SHORT_DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cShortDescription()));
            reqBuilder.addPart("SHORT_DESCRIPTION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cShortDescription()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxDocumentation().equals(npwp.getF1cDocumentation())) {
                multipart.addFormField("SETDOCUMENTATION" + index, "1");
                reqBuilder.addPart("SETDOCUMENTATION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETDOCUMENTATION" + index, "0");
                reqBuilder.addPart("SETDOCUMENTATION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("DOCUMENTATION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cDocumentation()));
            reqBuilder.addPart("DOCUMENTATION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cDocumentation()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxVideoDescription().equals(npwp.getF1cVideoDescription())) {
                multipart.addFormField("SETVIDEO_DESCRIPTION" + index, "1");
                reqBuilder.addPart("SETVIDEO_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETVIDEO_DESCRIPTION" + index, "0");
                reqBuilder.addPart("SETVIDEO_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("VIDEO_DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cVideoDescription()));
            reqBuilder.addPart("VIDEO_DESCRIPTION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cVideoDescription()), ContentType.TEXT_PLAIN));

            if (npwp.getBxCollapsevc() != npwp.getF1cCollapsevc()) {
                multipart.addFormField("SETCOLLAPSEVC" + index, "1");
                reqBuilder.addPart("SETCOLLAPSEVC" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETCOLLAPSEVC" + index, "0");
                reqBuilder.addPart("SETCOLLAPSEVC" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("COLLAPSEVC" + index,
                    StringEscapeUtils.escapeJava("" + npwp.getF1cCollapsevc()));
            reqBuilder.addPart("COLLAPSEVC" + index, new StringBody(
                    StringEscapeUtils.escapeJava("" + npwp.getF1cCollapsevc()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxAdvants().equals(npwp.getF1cAdvants())) {
                multipart.addFormField("SETADVANTS" + index, "1");
                reqBuilder.addPart("SETADVANTS" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETADVANTS" + index, "0");
                reqBuilder.addPart("SETADVANTS" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("ADVANTS" + index, StringEscapeUtils.escapeJava(npwp.getF1cAdvants()));
            reqBuilder.addPart("ADVANTS" + index,
                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cAdvants()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxFilterProps().equals(npwp.getF1cFilterProps())) {
                multipart.addFormField("SETFILTER_PROPS" + index, "1");
                reqBuilder.addPart("SETFILTER_PROPS" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETFILTER_PROPS" + index, "0");
                reqBuilder.addPart("SETFILTER_PROPS" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("FILTER_PROPS" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cFilterProps()));
            reqBuilder.addPart("FILTER_PROPS" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cFilterProps()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxSeoAliasUrl().equals(npwp.getF1cSeoAliasUrl())
                    && npwp.getF1cSeoAliasUrl().length() > 3) {
                multipart.addFormField("SETSEO_ALIAS_URL" + index, "1");
                reqBuilder.addPart("SETSEO_ALIAS_URL" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSEO_ALIAS_URL" + index, "0");
                reqBuilder.addPart("SETSEO_ALIAS_URL" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SEO_ALIAS_URL" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cSeoAliasUrl()));
            reqBuilder.addPart("SEO_ALIAS_URL" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cSeoAliasUrl()), ContentType.TEXT_PLAIN));

            if (npwp.getBxSeoAliasUrl().length() <= 0 && npwp.getF1cSeoAliasUrl().length() <= 3
                    && npwp.getF1cname().length() > 0) {
                multipart.addFormField("SETSEO_ALIAS_URL_FROM_NAME" + index, "1");
                multipart.addFormField("SEO_ALIAS_URL_FROM_NAME" + index,
                        StringEscapeUtils.escapeJava(npwp.getF1cname()));
                reqBuilder.addPart("SETSEO_ALIAS_URL_FROM_NAME" + index,
                        new StringBody("1", ContentType.TEXT_PLAIN));
                reqBuilder.addPart("SEO_ALIAS_URL_FROM_NAME" + index, new StringBody(
                        StringEscapeUtils.escapeJava(npwp.getF1cname()), ContentType.TEXT_PLAIN));
            }

            if (!npwp.getBxSeoTitle().equals(npwp.getF1cSeoTitle())) {
                multipart.addFormField("SETSEO_TITLE" + index, "1");
                reqBuilder.addPart("SETSEO_TITLE" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSEO_TITLE" + index, "0");
                reqBuilder.addPart("SETSEO_TITLE" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SEO_TITLE" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoTitle()));
            reqBuilder.addPart("SEO_TITLE" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cSeoTitle()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxSeoH1().equals(npwp.getF1cSeoH1())) {
                multipart.addFormField("SETSEO_H1" + index, "1");
                reqBuilder.addPart("SETSEO_H1" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSEO_H1" + index, "0");
                reqBuilder.addPart("SETSEO_H1" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SEO_H1" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoH1()));
            reqBuilder.addPart("SEO_H1" + index,
                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cSeoH1()), ContentType.TEXT_PLAIN));

            index++;
        }

        try {
            if (logStr.length() > 0)
                cbLogsFacade.insertLog("INFO", "UPD SECT TO SEND ",
                        "<p style=\"font-size:10px !important;\">" + logStr + "</p>");
        } catch (Exception lgen) {
        }

        List<String> response = multipart.finish();

        for (String line : response) {
            sreply = sreply + line;
        }

        /*sreply = "{}";
                
        HttpEntity reqEntity = reqBuilder.build();
        httppost.setEntity(reqEntity);
                
        //System.out.println("executing request " + httppost.getRequestLine());
        try {
        CloseableHttpResponse clresponse = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            //clresponse.getStatusLine();
            HttpEntity resEntity = clresponse.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                //resEntity.getContent(); resEntity.getContentEncoding()
                try {
                    String responseString = EntityUtils.toString(resEntity, "UTF-8");
                    sreply = responseString;
                    EntityUtils.consume(resEntity);
                } catch(Exception ee)   {
                            
                }
            }
                    
        } finally {
            try {
                clresponse.close();
            } catch(Exception ee)   {
                
            }
        }
        } catch(Exception ee)   {
                    
        }*/

        try {
            JsonReader jsonReader = Json.createReader(new StringReader(sreply));
            JsonObject jobject = jsonReader.readObject();
            try {
                cbLogsFacade.insertLog("INFO", "SUCCESS OF PARSE SERVER REPLY",
                        "SUCCESS OF PARSE SERVER REPLY=" + jobject.toString());
            } catch (Exception lge) {

            }
            try {
                if (jobject.getString("critical_info", "").length() > 0)
                    cbLogsFacade.insertLog("CRITICAL_INFO", "SERVER REPLY DETAIL",
                            jobject.getString("critical_info", ""));
            } catch (Exception lge) {

            }
            try {
                if (jobject.getString("critical_errs", "").length() > 0)
                    cbLogsFacade.insertLog("CRITICAL_ERRS", "SERVER REPLY DETAIL",
                            jobject.getString("critical_errs", ""));
            } catch (Exception lge) {

            }
        } catch (Exception pe) {
            try {
                cbLogsFacade.insertLog("ERROR", "ERROR OF PARSE SERVER REPLY",
                        "ERROR OF PARSE SERVER REPLY" + sreply);
            } catch (Exception lge) {

            }
        }

    } catch (Exception ex) {
        try {
            cbLogsFacade.insertLog("ERROR", "ERROR of postMultipartSectUpd",
                    logStr + " ERROR of postMultipartSectUpd " + ex);
        } catch (Exception lge) {

        }
    }

    return reply;
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

@Deprecated
protected HttpResponse post(URI url, File requestContent, boolean authenticate) throws Exception {
    HttpPost method = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("param_name", new StringBody("value"));
    entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
    HttpResponse response = putOrPost(method, entity, authenticate);
    int status = response.getStatusLine().getStatusCode();
    if (status == SC_MOVED_TEMPORARILY) {
        String original = url.toString();
        url = URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
        if (!original.equals(url.toString())) {
            EntityUtils.consumeQuietly(response.getEntity());
            method = new HttpPost(url);
            entity = new MultipartEntity();
            entity.addPart("param_name", new StringBody("value"));
            entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
            response = putOrPost(method, entity, true);
        }// ww w . j  a v a 2s .c om
    }

    return response;
}

From source file:com.quwu.xinwo.release.Release_Activity.java

/**
 * ???//w w w.ja va 2 s  .  co  m
 * */
private String uploading3(String url, List<String> path, String goods_name, String good_description,
        String audiofile, String good_region, String city_region, String small_area, String twolevel_id,
        String three_id, String normal_use, String since, String user_id, String freight, String contactQQ,
        String whether_pack) throws ParseException, IOException {
    String result = null;
    HttpPost httpPost = new HttpPost(url);
    // httpPost.addHeader("Content-Type", "video/mpeg");
    // httpPost.addHeader("User-Agent", "imgfornote");
    // ?
    MultipartEntity reqEntity = new MultipartEntity();

    for (int i = 0; i < path.size(); i++) {// 
        File file1 = null;
        if (path.get(i).equals("drawable://" + R.drawable.fb_icn_video)
                || path.get(i).equals("drawable://" + R.drawable.fb_icn_carema)) {

        } else if (path.get(i).equals(CameraUtils.CAMERA_VIDEO)) {
            file1 = new File(path.get(i));
            // if (!file1.getAbsoluteFile().equals("")) {
            FileBody fileBody = new FileBody(file1);
            reqEntity.addPart("videofile", fileBody);
        } else {
            file1 = new File(path.get(i));
            // if (!file1.getAbsoluteFile().equals("")) {
            FileBody fileBody = new FileBody(file1);
            reqEntity.addPart("imagefile", fileBody);
            // }
        }
    }
    if (!audiofile.equals("")) {
        File file3 = new File(audiofile);// 
        if (!file3.getAbsoluteFile().equals("")) {
            FileBody fileBody = new FileBody(file3);
            reqEntity.addPart("audiofile", fileBody);
        }
    }
    StringBody type = new StringBody(goods_name);
    reqEntity.addPart("goods_name", type);
    StringBody type1 = new StringBody(good_description);
    reqEntity.addPart("good_description", type1);
    StringBody type2 = new StringBody(good_region);
    reqEntity.addPart("good_region", type2);
    StringBody type3 = new StringBody(city_region);
    reqEntity.addPart("city_region", type3);
    StringBody type4 = new StringBody(small_area);
    reqEntity.addPart("small_area", type4);
    StringBody type6 = new StringBody(twolevel_id);
    reqEntity.addPart("twolevel_id", type6);
    StringBody type19 = new StringBody(three_id);
    reqEntity.addPart("three_id", type19);
    StringBody type8 = new StringBody(normal_use);
    reqEntity.addPart("normal_use", type8);
    StringBody type14 = new StringBody(since);
    reqEntity.addPart("since", type14);
    StringBody type15 = new StringBody(user_id);
    reqEntity.addPart("user_id", type15);
    StringBody type16 = new StringBody(freight);
    reqEntity.addPart("freight", type16);
    StringBody type17 = new StringBody(contactQQ);
    reqEntity.addPart("contactQQ", type17);
    Log.e("contactQQ", contactQQ);
    Log.e("freight", freight);
    StringBody type20 = new StringBody(whether_pack);
    reqEntity.addPart("whether_pack", type20);
    httpPost.setEntity(reqEntity);
    // ?HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    // ?HttpResponse
    HttpResponse httpResponse = httpclient.execute(httpPost);
    // HttpStatus.SC_OK?
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // ?
        result = EntityUtils.toString(httpResponse.getEntity());
    } else {
        pd.dismiss();
    }
    return result;
}

From source file:org.ohmage.lib.OhmageApi.java

/**
 * Makes a call to the URL. The call will be a GET if 'postParameters' is
 * null and a POST if 'postParameters' is non-null, even if it is empty. If
 * it is a POST, 'isForm' will set it to be a "multipart/form-data" 
 * request, but if it is set to false it will default to a 
 * "application/x-www-form-urlencoded" request.<br />
 * <br />/*ww  w  . j a  va  2  s .  c  o  m*/
 * If the response has a Content-Type that suggests that it is JSON, it 
 * will check if the ohmage result is success or failure and throw an 
 * exception if it is failure.
 * 
 * @param url The URL which dictates the location to which the request
 *            should be made. This includes the scheme, which must be an
 *            HTTP scheme ("http" or "https"), a domain, an optional port,
 *            a path, and an optional query string. 
 * 
 * @param postParameters A map of keys to values for a POST call. The 
 *                    values must be a byte array to facilitate sending
 *                    things other than text such as images. If this is
 *                    null, the request will be a GET request; if this
 *                    is non-null, even if it is empty, it will force it
 *                    to be a POST call.
 * 
 * @param isForm This flag is used if the 'postParameters' is non-null and
 *              indicates whether this POST should be a 
 *              "multipart/form-data" request or not.
 * 
 * @return Returns the result from the server as a byte array. 
 * 
 * @throws ApiException Thrown if the URL is not an HTTP URL or if there
 *                      was an error communicating with the server.
 */
private byte[] makeRequest(final URL url, final Map<String, Object> postParameters, final boolean isForm)
        throws ApiException, RequestErrorException {

    // Create a default client to use to connect with.
    HttpClient httpClient = new DefaultHttpClient();

    // Build the request based on the parameters.
    HttpRequestBase request;
    if (postParameters == null) {
        // This is a GET request and the parameters are encoded in the URL.
        try {
            request = new HttpGet(url.toURI());
        } catch (URISyntaxException e) {
            throw new ApiException("There was an error building the request.", e);
        }
    } else {
        // This is a POST request and the parameter list must be built.
        try {
            HttpPost postRequest = new HttpPost(url.toURI());
            request = postRequest;

            // Build the parameter map which is called a "HttpEntity".
            HttpEntity entity;
            // It is a "multipart/form-data" request and the parameters
            // must be assigned to the 'entity'.
            if (isForm) {
                MultipartEntity multipartEntity = new MultipartEntity();
                entity = multipartEntity;

                for (String key : postParameters.keySet()) {
                    Object value = postParameters.get(key);

                    // If it is a File, add it to the entity list as an 
                    // attachment.
                    if (value instanceof File) {
                        multipartEntity.addPart(key, new FileBody((File) value));
                    }
                    // Otherwise, get its string value and add it as such.
                    else if (value != null) {
                        try {
                            multipartEntity.addPart(key, new StringBody(String.valueOf(value)));
                        } catch (UnsupportedEncodingException e) {
                            throw new ApiException("The value for key '" + key + "' could not be encoded.", e);
                        }
                    }
                }
            }
            // It is a "application/x-www-form-urlencoded" request and the
            // parameters can each be added as a string-string pair.
            else {
                List<BasicNameValuePair> items = new ArrayList<BasicNameValuePair>(postParameters.size());

                for (String key : postParameters.keySet()) {
                    Object value = postParameters.get(key);

                    if (value != null) {
                        items.add(new BasicNameValuePair(key, String.valueOf(value)));
                    }
                }

                try {
                    entity = new UrlEncodedFormEntity(items);
                } catch (UnsupportedEncodingException e) {
                    throw new ApiException("The parameter list could not be properly encoded.", e);
                }
            }
            postRequest.setEntity(entity);
        } catch (URISyntaxException e) {
            throw new ApiException("There was an error building the request.", e);
        }
    }

    // Make the request and get the response.
    HttpResponse httpResponse;
    try {
        httpResponse = httpClient.execute(request);
    } catch (ClientProtocolException e) {
        throw new ApiException("An HTTP protocol error occurred.", e);
    } catch (IOException e) {
        throw new ApiException("The connection was aborted.", e);
    }

    // Check the status code.
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    // If it is a redirect, get the new location and remake the request.
    if ((statusCode == 301) || (statusCode == 302)) {
        String newLocation = httpResponse.getFirstHeader("Location").getValue();

        try {
            return makeRequest(new URL(newLocation), postParameters, isForm);
        } catch (MalformedURLException e) {
            throw new ApiException("The server returned a bad redirect address: " + newLocation, e);
        }
    }
    // Otherwise, if it is is a non-success code, fail the request.
    else if (statusCode != 200) {
        throw new ApiException("There was an error connecting to the server: " + statusCode);
    }

    // Retrieve the server's response as an InputStream.
    InputStream content;
    try {
        content = httpResponse.getEntity().getContent();
    } catch (IOException e) {
        throw new ApiException("There was an error connecting to the response from the server.", e);
    }

    // Read the results as a byte array. This is used instead of a string 
    // to allow the function to me more open to different types of return 
    // values such as text, images, etc.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] chunk = new byte[CHUNK_SIZE];
    int amountRead;
    try {
        while ((amountRead = content.read(chunk)) != -1) {
            baos.write(chunk, 0, amountRead);
        }
    } catch (IOException e) {
        throw new ApiException("There was an error reading from the server.", e);
    }
    byte[] result = baos.toByteArray();

    // Finally, check the Content-Type to see if it suggests that this is
    // an ohmage JSON result. If so, check if it failed and, if so, throw
    // an exception.
    Header[] headers = httpResponse.getHeaders(CONTENT_TYPE_HEADER);
    String contentType = headers[0].getValue();
    if (CONTENT_TYPE_HTML.equals(contentType)) {
        checkFailure(result);
    }

    // Return the byte array.
    return result;
}

From source file:org.deegree.tools.metadata.InspireValidator.java

/**
 * main method to validate a metadata record using INSPIRE metadata validator
 * //from  w w w  .  j  a va2 s  . c  o m
 * @param element
 * @throws Exception
 */
private void validateINSPIRE(org.w3c.dom.Element element) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(Messages.get("validator"));
    // xml response: httpPost.addHeader("Accept", "application/xml");
    // html response
    httpPost.addHeader("Accept", "text/html");
    XMLFragment xml = new XMLFragment(element);
    File tmp = new File("tmp.xml");
    tmp.deleteOnExit();
    xml.write(new FileWriter(tmp));
    FileBody dataFile = new FileBody(new File("tmp.xml"));
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("dataFile", dataFile);
    httpPost.setEntity(reqEntity);

    HttpResponse response = httpclient.execute(httpPost);
    parseServiceResponse(response);

}

From source file:org.kuali.ole.web.DocumentServlet_AT.java

/**
 * Method creates the bag from the test case folder then sends to the document store application and captures the response
 *///  www. j  ava 2 s  .  c  om
@Test
public void testMultiPartIngestForWorkLicense() {
    try {
        inputDir = new File(this.getClass().getResource("license/ingest").toURI());
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();
        CompressUtils compressUtils = new CompressUtils();
        File zipFile = compressUtils.createZippedBagFile(inputDir);
        FileBody uploadFilePart = new FileBody(zipFile);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("upload-file", uploadFilePart);
        httpPost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httpPost);
        zipFile.delete();
        logger.info("STATUS : " + response.getStatusLine());
        HttpEntity respEntity = response.getEntity();
        InputStream outcome = respEntity.getContent();
        File respFile = File.createTempFile("DocStore Ingest-", "-Response File.zip");
        IOUtils.copy(outcome, new FileOutputStream(respFile));
        List<File> resp = compressUtils
                .getAllFilesList(compressUtils.extractZippedBagFile(respFile.getAbsolutePath(), null));
        for (File file : resp) {
            if (file.getName().equalsIgnoreCase("response.xml")) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                logger.info("RESPONSE: " + file.getName());
                String line = null;
                while ((line = br.readLine()) != null)
                    logger.info(line);
                this.response = new ResponseHandler().toObject(FileUtils.readFileToString(file));
            } else
                logger.info("File : " + file.getName());
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        //fail("Failed Test: ");

    }
}

From source file:org.kuali.ole.web.DocumentServlet_AT.java

@Test
public void testMultiPartCheckOutForWorkLicense() {
    try {/*from www  .  ja  v  a2  s.  c  om*/
        if (response == null)
            this.testMultiPartIngestForWorkLicense();
        Request request = new Request();
        request.setUser(response.getUser());
        request.setOperation("checkOut");
        for (ResponseDocument doc : response.getDocuments()) {
            RequestDocument rd = new RequestDocument();
            rd.setId(doc.getId());
            rd.setCategory(doc.getCategory());
            rd.setType(doc.getType());
            rd.setFormat(doc.getFormat());
            rd.setUuid(doc.getUuid());
            request.getRequestDocuments().add(rd);
        }
        String xml = requestHandler.toXML(request);

        File folder = File.createTempFile("ds-", "-inp");
        folder.delete();
        folder.mkdirs();
        FileOutputStream fos = new FileOutputStream(
                new File(folder.getAbsolutePath() + File.separator + "request.xml"));
        IOUtils.copy(IOUtils.toInputStream(xml), fos);
        fos.close();
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();
        CompressUtils compressUtils = new CompressUtils();
        File zipFile = compressUtils.createZippedBagFile(folder);
        FileBody uploadFilePart = new FileBody(zipFile);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("upload-file", uploadFilePart);
        httpPost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httpPost);
        zipFile.delete();
        logger.info("STATUS : " + response.getStatusLine());
        HttpEntity respEntity = response.getEntity();
        InputStream outcome = respEntity.getContent();
        File respFile = File.createTempFile("DocStore CheckOut-", "-Response File.zip");
        IOUtils.copy(outcome, new FileOutputStream(respFile));
        List<File> resp = compressUtils
                .getAllFilesList(compressUtils.extractZippedBagFile(respFile.getAbsolutePath(), null));
        for (File file : resp) {
            if (file.getName().equalsIgnoreCase("response.xml")) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                logger.info("RESPONSE: " + file.getName());
                String line = null;
                while ((line = br.readLine()) != null)
                    logger.info(line);
            } else
                logger.info("File : " + file.getName());
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail("Failed Test: ");

    }
}

From source file:org.kuali.ole.web.DocumentServlet_AT.java

@Test
public void testMultiPartStaticCheckOutForWorkLicense() {
    try {//from w w  w  .  j av a 2s.c  o m
        inputDir = new File(this.getClass().getResource("license/checkout").toURI());
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();
        CompressUtils compressUtils = new CompressUtils();
        File zipFile = compressUtils.createZippedBagFile(inputDir);
        FileBody uploadFilePart = new FileBody(zipFile);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("upload-file", uploadFilePart);
        httpPost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httpPost);
        zipFile.delete();
        logger.info("STATUS : " + response.getStatusLine());
        HttpEntity respEntity = response.getEntity();
        InputStream outcome = respEntity.getContent();
        File respFile = File.createTempFile("DocStore CheckOut-", "-Response File.zip");
        logger.info("Response is at loc.: " + respFile.getAbsolutePath());
        IOUtils.copy(outcome, new FileOutputStream(respFile));
        List<File> resp = compressUtils
                .getAllFilesList(compressUtils.extractZippedBagFile(respFile.getAbsolutePath(), null));
        for (File file : resp) {
            if (file.getName().equalsIgnoreCase("response.xml")) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                logger.info("RESPONSE: " + file.getName());
                String line = null;
                while ((line = br.readLine()) != null)
                    logger.info(line);
            } else
                logger.info("File : " + file.getName());
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail("Failed Test: ");

    }
}