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:com.strathclyde.highlightingkeyboard.HttpPostAsyncTask.java

/**
 * perform the data upload via HTTP POST
 *//*  w w w . j  a v a 2 s . c  o  m*/
@Override
protected Boolean doInBackground(String... params) {
    String filePath = params[0];

    //Log.i("AsyncTask", "received file to upload "+filePath);

    String url;
    if (insert)
        url = "http://150.140.15.50/oats/receivedb.php";
    else
        url = "http://150.140.15.50/oats/receivedb_no_insert.php";
    file = new File(filePath);
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addBinaryBody("file", file, ContentType.create("application/octet-stream"), file.getName())
                .build();

        post.setEntity(httpEntity);
        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //Log.i("AsyncTask", "Upload OK"+filePath);
            String responseString = EntityUtils.toString(response.getEntity());
            //Log.i("AsyncTask", responseString);
            if (responseString.contains("Done")) {
                return true;
            }
        } else {
            //Log.i("AsyncTask", "Upload failed: "+response.getStatusLine().getStatusCode());
            //Log.i("AsyncTask", "Upload failed: "+EntityUtils.toString(response.getEntity()));
            //Toast.makeText(c, "Upload failed: "+response.getStatusLine().getStatusCode()+ " db saved locally to "+filePath, Toast.LENGTH_SHORT).show();
            return false;
        }

    } catch (Exception e) {
        // show error
        e.printStackTrace();
        return false;
    }

    return false;

}

From source file:com.releasequeue.server.ReleaseQueueServer.java

@Override
public HttpResponse uploadPackage(FilePath packagePath, String distribution, String component)
        throws MalformedURLException, IOException {
    String repoType = FilenameUtils.getExtension(packagePath.toString());

    String uploadPath = String.format("%s/%s/repositories/%s/packages?distribution=%s&component=%s",
            this.basePath, this.userName, repoType, distribution, component);
    URL uploadPackageUrl = new URL(this.serverUrl, uploadPath);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(uploadPackageUrl.toString());
    setAuthHeader(uploadFile);/*from   ww  w  .j a v a 2 s. co m*/

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(packagePath.toString()), ContentType.APPLICATION_OCTET_STREAM,
            packagePath.getName());
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    HttpResponse response = httpClient.execute(uploadFile);
    return response;
}

From source file:mesquite.zephyr.GarliRunnerCIPRes.GarliRunnerCIPRes.java

public Object getProgramArguments(String dataFileName, String configFilePath, boolean isPreflight) {
    MultipartEntityBuilder arguments = MultipartEntityBuilder.create();

    arguments.addTextBody("vparam.user_conffile_", "1");
    arguments.addTextBody("vparam.userconffilethere_", "1");
    arguments.addTextBody("vparam.userconffileconfirm_", "1");

    arguments.addTextBody("vparam.searchreps_value_", "" + numRuns);

    return arguments;
}

From source file:com.kurento.test.recorder.RecorderIT.java

private void testRecord(String handler, int statusCode) throws IOException {
    // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy())
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler);
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File("small");
    URL small = new URL(VideoURLs.map.get("small-webm"));
    FileUtils.copyURLToFile(small, file);
    FileBody fb = new FileBody(file);
    multipartEntity.addPart("file", fb);

    HttpEntity httpEntity = multipartEntity.build();
    post.setEntity(httpEntity);// w w  w. j  a  v a 2  s. c om

    EntityUtils.consume(httpEntity);
    HttpResponse response = client.execute(post);
    final int responseStatusCode = response.getStatusLine().getStatusCode();

    log.info("Response Status Code: {}", responseStatusCode);
    log.info("Deleting tmp file: {}", file.delete());

    Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);
}

From source file:com.behance.sdk.asynctasks.BehanceSDKCreateProjectDraftAsyncTask.java

protected BehanceSDKAsyncTaskResultWrapper<String> doInBackground(
        BehanceSDKCreateProjectDraftTaskParams... paramVarArgs) {
    BehanceSDKAsyncTaskResultWrapper localBehanceSDKAsyncTaskResultWrapper = new BehanceSDKAsyncTaskResultWrapper();
    Object localObject2 = paramVarArgs[0];
    for (;;) {/*from  w w w. j av  a 2  s.  c om*/
        try {
            paramVarArgs = new HashMap(1);
            paramVarArgs.put("clientId", ((BehanceSDKCreateProjectDraftTaskParams) localObject2).getClientId());
            Object localObject1 = BehanceSDKUrlUtil.getUrlFromTemplate(
                    "{server_root_url}/v2/project/editor?{key_client_id_param}={clientId}", paramVarArgs);
            Object localObject3 = BehanceSDKUserManager.getInstance().checkExpiryAndGetAccessToken();
            paramVarArgs = (BehanceSDKCreateProjectDraftTaskParams[]) localObject1;
            if (localObject3 != null) {
                paramVarArgs = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject1, "access_token",
                        localObject3);
            }
            localObject1 = ((BehanceSDKCreateProjectDraftTaskParams) localObject2)
                    .getBehanceSDKProjectDraftOptions();
            localObject2 = new HttpPost(paramVarArgs);
            if (localObject1 != null) {
                localObject3 = MultipartEntityBuilder.create();
                ContentType localContentType = ContentType.create("text/plain", "UTF-8");
                paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectTitle();
                if (!TextUtils.isEmpty(paramVarArgs)) {
                    ((MultipartEntityBuilder) localObject3).addTextBody("title", paramVarArgs,
                            localContentType);
                }
                paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectDescription();
                if (!TextUtils.isEmpty(paramVarArgs)) {
                    ((MultipartEntityBuilder) localObject3).addTextBody("description", paramVarArgs,
                            localContentType);
                }
                paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectTags();
                if (!TextUtils.isEmpty(paramVarArgs)) {
                    ((MultipartEntityBuilder) localObject3).addTextBody("tags", paramVarArgs, localContentType);
                }
                paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getCreativeFields();
                if (!TextUtils.isEmpty(paramVarArgs)) {
                    ((MultipartEntityBuilder) localObject3).addTextBody("fields", paramVarArgs,
                            localContentType);
                }
                if (((BehanceSDKProjectDraftOptions) localObject1).isProjectContainsAdultContent()) {
                    paramVarArgs = "1";
                    ((MultipartEntityBuilder) localObject3).addTextBody("mature_content", paramVarArgs,
                            localContentType);
                    paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getProjectCopyrightSettings();
                    if (paramVarArgs != null) {
                        ((MultipartEntityBuilder) localObject3).addTextBody("license", paramVarArgs.getValue(),
                                localContentType);
                    }
                    paramVarArgs = ((BehanceSDKProjectDraftOptions) localObject1).getCoverImage();
                    if (paramVarArgs != null) {
                        ((MultipartEntityBuilder) localObject3).addPart("image", new FileBody(paramVarArgs));
                    }
                    ((HttpPost) localObject2).setEntity(((MultipartEntityBuilder) localObject3).build());
                }
            } else {
                paramVarArgs = BehanceSDKHTTPUtils.doHTTPPost((HttpPost) localObject2);
                if (paramVarArgs.getStatusCode() != 201) {
                    localBehanceSDKAsyncTaskResultWrapper.setExceptionOccurred(true);
                    localBehanceSDKAsyncTaskResultWrapper
                            .setException(new BehanceSDKException(paramVarArgs.getReasonPhrase()));
                    return localBehanceSDKAsyncTaskResultWrapper;
                }
                localBehanceSDKAsyncTaskResultWrapper.setExceptionOccurred(false);
                localBehanceSDKAsyncTaskResultWrapper.setResult(
                        ((JSONObject) new JSONObject(paramVarArgs.getResponseString()).get("project"))
                                .optString("id"));
                return localBehanceSDKAsyncTaskResultWrapper;
            }
        } catch (Throwable paramVarArgs) {
            localBehanceSDKAsyncTaskResultWrapper.setExceptionOccurred(true);
            localBehanceSDKAsyncTaskResultWrapper.setException(new BehanceSDKException(paramVarArgs));
            return localBehanceSDKAsyncTaskResultWrapper;
        }
        paramVarArgs = "0";
    }
}

From source file:com.wattzap.model.social.SelfLoopsAPI.java

public static int uploadActivity(String email, String passWord, String fileName, String note)
        throws IOException {
    JSONObject jsonObj = null;/*  ww  w.  j a v  a2 s.co m*/

    FileInputStream in = null;
    GZIPOutputStream out = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("enctype", "multipart/mixed");

        in = new FileInputStream(fileName);
        // Create stream to compress data and write it to the to file.
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        out = new GZIPOutputStream(obj);

        // Copy bytes from one stream to the other
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes_read);
        }
        out.close();
        in.close();

        ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"),
                fileName);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN))
                .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin)
                .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build();

        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            switch (code) {
            case 200:

                HttpEntity respEntity = response.getEntity();

                if (respEntity != null) {
                    // EntityUtils to get the response content
                    String content = EntityUtils.toString(respEntity);
                    //System.out.println(content);
                    JSONParser jsonParser = new JSONParser();
                    jsonObj = (JSONObject) jsonParser.parse(content);
                }

                break;
            case 403:
                throw new RuntimeException(
                        "Authentification failure " + email + " " + response.getStatusLine());
            default:
                throw new RuntimeException("Error " + code + " " + response.getStatusLine());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }

        int activityId = ((Long) jsonObj.get("activity_id")).intValue();

        // parse error code
        int error = ((Long) jsonObj.get("error_code")).intValue();
        if (activityId == -1) {
            String message = (String) jsonObj.get("message");
            switch (error) {
            case 102:
                throw new RuntimeException("Empty TCX file " + fileName);
            case 103:
                throw new RuntimeException("Invalide TCX Format " + fileName);
            case 104:
                throw new RuntimeException("TCX Already Present " + fileName);
            case 105:
                throw new RuntimeException("Invalid XML " + fileName);
            case 106:
                throw new RuntimeException("invalid compression algorithm");
            case 107:
                throw new RuntimeException("Invalid file mime types");
            default:
                throw new RuntimeException(message + " " + error);
            }
        }

        return activityId;
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        httpClient.close();
    }
}

From source file:org.brunocvcunha.jiphy.requests.JiphyUploadRequest.java

/**
 * Creates required multipart entity with the image binary
 * /*from w  ww.  j a  v a2 s.  co m*/
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException
 * @throws IOException
 */
protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", file);

    HttpEntity entity = builder.build();
    return entity;
}

From source file:ezbake.azkaban.manager.UploadManager.java

/**
 * Uploads the zip file to Azkaban//from   w w  w . j a v a 2  s  . c o m
 *
 * @return {@link ezbake.azkaban.manager.result.UploaderResult} status of the upload
 */
public UploaderResult uploadZip() {
    try {
        HttpEntity entity = MultipartEntityBuilder.create().addTextBody("session.id", sessionId)
                .addTextBody("ajax", "upload")
                .addBinaryBody("file", zip, ContentType.create("application/zip"), zip.getName())
                .addTextBody("project", projectName).build();

        HttpPost post = new HttpPost(endPoint);
        post.setEntity(entity);

        String json = HttpManager.post(post);
        return (UploaderResult) JsonUtil.deserialize(json, UploaderResult.class);
    } catch (Exception ex) {
        return new UploaderResult(ex.getMessage());
    }
}

From source file:cn.vlabs.duckling.vwb.service.ddl.RestClient.java

private HttpEntity buildMultiPartForm(String dataFieldName, String filename, InputStream stream,
        String... params) {//from   w w w . ja v a2  s.c o m
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody(dataFieldName, stream, ContentType.DEFAULT_BINARY, filename);

    if (params != null) {
        for (int i = 0; i < params.length / 2; i++) {
            StringBody contentBody = new StringBody(params[i * 2 + 1], DEFAULT_CONTENT_TYPE);
            builder.addPart(params[i * 2], contentBody);
        }
    }

    HttpEntity reqEntity = builder.setCharset(DEFAULT_CHARSET).build();
    return reqEntity;
}

From source file:com.redhat.jenkins.plugins.bayesian.Bayesian.java

public BayesianStepResponse submitStackForAnalysis(Collection<FilePath> manifests) throws BayesianException {
    String stackAnalysesUrl = getApiUrl() + "/stack-analyses";
    HttpPost httpPost = new HttpPost(stackAnalysesUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (FilePath manifest : manifests) {
        byte[] content = null;
        try (InputStream in = manifest.read()) {
            content = ByteStreams.toByteArray(in);
            builder.addBinaryBody("manifest[]", content, ContentType.DEFAULT_BINARY, manifest.getName());
        } catch (IOException | InterruptedException e) {
            throw new BayesianException(e);
        } finally {
            content = null;/*from  w  ww.  ja  va 2  s. c  o  m*/
        }
    }
    HttpEntity multipart = builder.build();
    builder = null;
    httpPost.setEntity(multipart);
    httpPost.setHeader("Authorization", "Bearer " + getAuthToken());

    BayesianResponse responseObj = null;
    Gson gson;
    try (CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(httpPost)) {
        HttpEntity entity = response.getEntity();
        // Yeah, the endpoint actually returns 200 from some reason;
        // I wonder what happened to the good old-fashioned 202 :)
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new BayesianException("Bayesian error: " + response.getStatusLine().getStatusCode());
        }

        Charset charset = ContentType.get(entity).getCharset();
        try (InputStream is = entity.getContent();
                Reader reader = new InputStreamReader(is,
                        charset != null ? charset : HTTP.DEF_CONTENT_CHARSET)) {
            gson = new GsonBuilder().create();
            responseObj = gson.fromJson(reader, BayesianResponse.class);
            String analysisUrl = stackAnalysesUrl + "/" + responseObj.getId();
            return new BayesianStepResponse(responseObj.getId(), "", analysisUrl, true);
        }
    } catch (IOException e) {
        throw new BayesianException("Bayesian error", e);
    } finally {
        // just to be sure...
        responseObj = null;
        httpPost = null;
        multipart = null;
        gson = null;
    }
}