Example usage for org.apache.http.entity.mime MultipartEntityBuilder create

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

/**
 * This method is use to post data in multidata format
 * @param url/*from   w ww  .  ja v a 2s .co  m*/
 *          - backend url
 * @param mobileApplicationBean
 *          - Bean class of the mobile application
 * @param headers
 *          - header files
 */
public static String doPostMultiData(String url, MobileApplicationBean mobileApplicationBean,
        Map<String, String> headers) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    // initializing headers
    if (headers != null && headers.size() > 0) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            httpPost.setHeader(key, headers.get(key));
        }
    }
    MultipartEntityBuilder reqEntity;
    reqEntity = MultipartEntityBuilder.create();
    reqEntity.addPart("version",
            new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("provider",
            new StringBody(mobileApplicationBean.getProvider(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("markettype",
            new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("platform",
            new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("description",
            new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA));
    FileBody bannerImageFile = new FileBody(mobileApplicationBean.getBannerFilePath());
    reqEntity.addPart("bannerFile", bannerImageFile);
    FileBody iconImageFile = new FileBody(mobileApplicationBean.getIconFile());
    reqEntity.addPart("iconFile", iconImageFile);
    FileBody screenShot1 = new FileBody(mobileApplicationBean.getScreenShot1File());
    reqEntity.addPart("screenshot1File", screenShot1);
    FileBody screenShot2 = new FileBody(mobileApplicationBean.getScreenShot2File());
    reqEntity.addPart("screenshot2File", screenShot2);
    FileBody screenShot3 = new FileBody(mobileApplicationBean.getScreenShot3File());
    reqEntity.addPart("screenshot3File", screenShot3);
    reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("mobileapp",
            new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("sso_ssoProvider",
            new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("appmeta",
            new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA));

    final HttpEntity entity = reqEntity.build();
    httpPost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = "";
    try {
        responseBody = httpClient.execute(httpPost, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseBody;
}

From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient/*from  w ww.  j a v a 2 s . c o  m*/
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }

    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL
            + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);

    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}",
            ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody(
            "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}",
            ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);

    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);

    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));

        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {

            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
        // String output = br.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // postInternal(post);
}

From source file:org.apache.stanbol.workflow.jersey.writers.ContentItemWriter.java

@Override
public void writeTo(ContentItem ci, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    //(0) handle default dataType
    Map<String, Object> reqProp = ContentItemHelper.getRequestPropertiesContentPart(ci);
    boolean omitMetadata = isOmitMetadata(reqProp);
    if (!MULTIPART.isCompatible(mediaType)) { //two possible cases
        if (!omitMetadata) { //  (1) just return the RDF data
            //(1.a) Backward support for default dataType if no Accept header is set
            StringBuilder ctb = new StringBuilder();
            if (mediaType.isWildcardType() || TEXT_PLAIN_TYPE.isCompatible(mediaType)
                    || APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType)) {
                ctb.append(APPLICATION_LD_JSON);
            } else {
                ctb.append(mediaType.getType()).append('/').append(mediaType.getSubtype());
            }/*ww w  . j  av  a2s  .  c  o  m*/
            ctb.append(";charset=").append(UTF8.name());
            String contentType = ctb.toString();
            httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
            try {
                serializer.serialize(entityStream, ci.getMetadata(), contentType);
            } catch (UnsupportedSerializationFormatException e) {
                throw new WebApplicationException("The enhancement results "
                        + "cannot be serialized in the requested media type: " + mediaType.toString(),
                        Response.Status.NOT_ACCEPTABLE);
            }
        } else { //  (2) return a single content part
            Entry<UriRef, Blob> contentPart = getBlob(ci, Collections.singleton(mediaType.toString()));
            if (contentPart == null) { //no alternate content with the requeste media type
                throw new WebApplicationException("The requested enhancement chain has not created an "
                        + "version of the parsed content in the reuqest media type " + mediaType.toString(),
                        Response.Status.UNSUPPORTED_MEDIA_TYPE);
            } else { //found -> stream the content to the client
                //NOTE: This assumes that the presence of a charset
                //      implies reading/writing character streams
                String requestedCharset = mediaType.getParameters().get("charset");
                String blobCharset = contentPart.getValue().getParameter().get("charset");
                Charset readerCharset = blobCharset == null ? UTF8 : Charset.forName(blobCharset);
                Charset writerCharset = requestedCharset == null ? null : Charset.forName(requestedCharset);
                if (writerCharset != null && !writerCharset.equals(readerCharset)) {
                    //we need to transcode
                    Reader reader = new InputStreamReader(contentPart.getValue().getStream(), readerCharset);
                    Writer writer = new OutputStreamWriter(entityStream, writerCharset);
                    IOUtils.copy(reader, writer);
                    IOUtils.closeQuietly(reader);
                } else { //no transcoding
                    if (requestedCharset == null && blobCharset != null) {
                        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE,
                                mediaType.toString() + "; charset=" + blobCharset);
                    }
                    InputStream in = contentPart.getValue().getStream();
                    IOUtils.copy(in, entityStream);
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } else { // multipart mime requested!
        final String charsetName = mediaType.getParameters().get("charset");
        final Charset charset = charsetName != null ? Charset.forName(charsetName) : UTF8;
        MediaType rdfFormat;
        String rdfFormatString = getRdfFormat(reqProp);
        if (rdfFormatString == null || rdfFormatString.isEmpty()) {
            rdfFormat = DEFAULT_RDF_FORMAT;
        } else {
            try {
                rdfFormat = MediaType.valueOf(rdfFormatString);
                if (rdfFormat.getParameters().get("charset") == null) {
                    //use the charset of the default RDF format
                    rdfFormat = new MediaType(rdfFormat.getType(), rdfFormat.getSubtype(),
                            DEFAULT_RDF_FORMAT.getParameters());
                }
            } catch (IllegalArgumentException e) {
                throw new WebApplicationException(
                        "The specified RDF format '" + rdfFormatString
                                + "' (used to serialize all RDF parts of "
                                + "multipart MIME responses) is not a well formated MIME type",
                        Response.Status.BAD_REQUEST);
            }
        }
        //(1) setting the correct header
        String contentType = String.format("%s/%s; charset=%s; boundary=%s", mediaType.getType(),
                mediaType.getSubtype(), charset.toString(), CONTENT_ITEM_BOUNDARY);
        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setBoundary(CONTENT_ITEM_BOUNDARY);
        //HttpMultipart entity = new HttpMultipart("from-data", charset ,CONTENT_ITEM_BOUNDARY);
        //(2) serialising the metadata
        if (!isOmitMetadata(reqProp)) {
            entityBuilder.addPart("metadata",
                    new ClerezzaContentBody(ci.getUri().getUnicodeString(), ci.getMetadata(), rdfFormat));
            //                entity.addBodyPart(new FormBodyPart("metadata", new ClerezzaContentBody(
            //                    ci.getUri().getUnicodeString(), ci.getMetadata(),
            //                    rdfFormat)));
        }
        //(3) serialising the Content (Bloby)
        //(3.a) Filter based on parameter
        List<Entry<UriRef, Blob>> includedBlobs = filterBlobs(ci, reqProp);
        //(3.b) Serialise the filtered
        if (!includedBlobs.isEmpty()) {
            Map<String, ContentBody> contentParts = new LinkedHashMap<String, ContentBody>();
            for (Entry<UriRef, Blob> entry : includedBlobs) {
                Blob blob = entry.getValue();
                ContentType ct = ContentType.create(blob.getMimeType());
                String cs = blob.getParameter().get("charset");
                if (StringUtils.isNotBlank(cs)) {
                    ct = ct.withCharset(cs);
                }
                contentParts.put(entry.getKey().getUnicodeString(), new InputStreamBody(blob.getStream(), ct));
            }
            //add all the blobs
            entityBuilder.addPart("content",
                    new MultipartContentBody(contentParts, CONTENT_PARTS_BOUNDERY, MULTIPART_ALTERNATE));
        } //else no content to include
        Set<String> includeContentParts = getIncludedContentPartURIs(reqProp);
        if (includeContentParts != null) {
            //(4) serialise the Request Properties
            if (includeContentParts.isEmpty()
                    || includeContentParts.contains(REQUEST_PROPERTIES_URI.getUnicodeString())) {
                JSONObject object;
                try {
                    object = toJson(reqProp);
                } catch (JSONException e) {
                    String message = "Unable to convert Request Properties " + "to JSON (values : " + reqProp
                            + ")!";
                    log.error(message, e);
                    throw new WebApplicationException(message, Response.Status.INTERNAL_SERVER_ERROR);
                }
                entityBuilder.addTextBody(REQUEST_PROPERTIES_URI.getUnicodeString(), object.toString(),
                        ContentType.APPLICATION_JSON.withCharset(UTF8));
            }
            //(5) additional RDF metadata stored in contentParts
            for (Entry<UriRef, TripleCollection> entry : getContentParts(ci, TripleCollection.class)
                    .entrySet()) {
                if (includeContentParts.isEmpty() || includeContentParts.contains(entry.getKey())) {
                    entityBuilder.addPart(entry.getKey().getUnicodeString(), new ClerezzaContentBody(null, //no file name
                            entry.getValue(), rdfFormat));
                } // else ignore this content part
            }
        }
        entityBuilder.build().writeTo(entityStream);
    }

}

From source file:org.teiid.arquillian.IntegrationTestRestWebserviceGeneration.java

@Test
public void testSemanticVersion() throws Exception {
    String vdb = ObjectConverterUtil.convertFileToString(UnitTestUtil.getTestDataFile("sample-vdb.xml"));
    vdb = StringUtil.replace(vdb, "name=\"sample\" version=\"1\"", "name=\"sample\" version=\"2.1.1\"");
    admin.deploy("sample-vdb.xml", new ByteArrayInputStream(vdb.getBytes("UTF-8")));
    assertTrue(AdminUtil.waitForVDBLoad(admin, "sample", "2.1.1", 3));

    this.internalConnection = TeiidDriver.getInstance()
            .connect("jdbc:teiid:sample@mm://localhost:31000;user=user;password=user", null);

    execute("SELECT * FROM Txns.G1"); //$NON-NLS-1$
    this.internalResultSet.next();

    assertTrue("sample_2.1.1.war not found", AdminUtil.waitForDeployment(admin, "sample_2.1.1.war", 5));

    HttpEntity entity = MultipartEntityBuilder.create().addTextBody("p1", "456").build();

    String response = httpMultipartPost(entity, "http://localhost:8080/sample_2.1.1/View/g1post");
    assertEquals("response did not match expected",
            "<rows p1=\"456\" p2=\"1\"><row><e1>ABCDEFGHIJ</e1><e2>0</e2></row></rows>", response);

    admin.undeploy("sample-vdb.xml");
    Thread.sleep(2000);/*from  www  .j  a  v a2  s.  c o  m*/
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * @throws MLHttpClientException/*from   w w  w . j a  va 2s.  c  o  m*/
 */
public CloseableHttpResponse predictFromCSV(long modelId, String resourcePath) throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/models/predict");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("modelId", new StringBody(modelId + "", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));

        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetesPredict.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to predict from csv " + resourcePath, e);
    }
}

From source file:io.swagger.client.api.CameraApi.java

/**
* Start recording a movie/*from  w ww.  j ava2  s .c o m*/
* 
 * @return void
*/
public void captureStartPost() throws TimeoutException, ExecutionException, InterruptedException, ApiException {
    Object postBody = null;

    // create path and map variables
    String path = "/capture/start".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody,
                headerParams, formParams, contentType, authNames);
        if (localVarResponse != null) {
            return;
        } else {
            return;
        }
    } catch (ApiException ex) {
        throw ex;
    } catch (InterruptedException ex) {
        throw ex;
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof VolleyError) {
            VolleyError volleyError = (VolleyError) ex.getCause();
            if (volleyError.networkResponse != null) {
                throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
            }
        }
        throw ex;
    } catch (TimeoutException ex) {
        throw ex;
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Should only be called from uploadLogs(). Compresses all files that belong
 to the given log set, and uploads all compressed files to the server. */
private boolean uploadLogs(final String logSet) {
    if (logSet == null)
        return false;

    File logsDir = getLogsDir();/*from   www  . j  av  a 2  s  .c  o  m*/
    if (logsDir == null)
        return false;
    gzipLogs(logsDir, logSet);

    // Uploading only gz'd files
    FilenameFilter gzFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".gz");
        }
    };
    File[] toUpload = logsDir.listFiles(gzFilter);

    String url = getUploadUrl();
    if (url == null) {
        /* This means the server is unable to accept the logs. */
        keepRecents(toUpload, 100);
        return false;
    }

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN));

    ContentType ct = ContentType.create("x-application/gzip");
    for (File f : toUpload) {
        entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName()));
    }
    post.setEntity(entity.build());

    boolean success = false;
    try (CloseableHttpResponse response = client.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        Log.log(Level.INFO, "Log upload result: {0}", status);
        if (status == HttpStatus.SC_OK) { // 200
            for (File f : toUpload) {
                try {
                    f.delete();
                } catch (SecurityException ex) {
                }
            }
            success = true;
        } else {
            LogRecord rec = new LogRecord(Level.INFO, "Server Err");
            rec.setParameters(new Object[] { url, "Status: " + status });
            getLogger().log(rec);
        }

        HttpEntity rspEntity = response.getEntity();
        EntityUtils.consume(rspEntity);
        client.close();
    } catch (IOException ex) {
        Log.log(ex);
    }

    keepRecents(toUpload, 100); // In case of exceptions or errors
    return success;
}

From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java

/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient//from w w  w. j  a v  a2  s . c o m
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }

    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL
            + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);

    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}",
            ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody(
            "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}",
            ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);

    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);

    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));

        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {

            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
        // String output = br.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

    send(post);
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java

/**
 * attach log using run id/*from   w  w w  .  j  a  v a2  s  . c  o  m*/
 * 
 * @param token
 *            - token generate using username and password
 * @param projectID
 * @param releaseID
 * @param cycleID
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID,
        long testCaseRunId, File filePath) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:com.licryle.httpposter.HttpPoster.java

/**
 * Builds the {@link _ProgressiveEntity} that we will send to the server.
 * Takes for input an {@link HttpConfiguration} that contains the Post
 * variables and File Names to send./*from   w  w  w.  j  av a  2s .  c om*/
 *
 * @param mConf Configuration of the POST request to be processed.
 * @return A ProgressiveEntity which progress can be tracked as we send it to
 * the server.
 *
 * @throws IOException When a file in the list of files from
 * {@link HttpConfiguration#getFiles()} cannot be read.
 *
 * @see {@link com.licryle.httpposter.HttpPoster._ProgressiveEntity}
 * @see {@link com.licryle.httpposter.HttpConfiguration}
 */
protected _ProgressiveEntity _buildEntity(HttpConfiguration mConf) throws IOException {
    Log.d("HttpPoster", String.format("_buildEntity: Entering for Instance %d", _iInstanceId));

    /********* Build request content *********/
    MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setBoundary(mConf.getHTTPBoundary());

    int iFileNb = 0;
    Iterator mFiles = mConf.getFiles().iterator();
    while (mFiles.hasNext()) {
        final File mFile = (File) mFiles.next();

        try {
            mBuilder.addBinaryBody("file_" + iFileNb, mFile, ContentType.DEFAULT_BINARY, mFile.getName());
        } catch (Exception e) {
            throw new IOException();
        }

        iFileNb++;
    }

    Iterator mArgs = mConf.getArgs().entrySet().iterator();
    while (mArgs.hasNext()) {
        Map.Entry mPair = (Map.Entry) mArgs.next();

        mBuilder.addTextBody((String) mPair.getKey(), (String) mPair.getValue(),
                ContentType.MULTIPART_FORM_DATA);
    }

    Log.d("HttpPoster", String.format("_buildEntity: Leaving for Instance %d", _iInstanceId));

    return new _ProgressiveEntity(mBuilder.build(), this);
}