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:info.debatty.sparkpackages.maven.plugin.PublishMojo.java

@Override
public final void realexe() throws MojoFailureException {

    File zip_file = new File(getZipPath());
    byte[] zip_base64 = null;
    try {/*w w w  . j  a  v  a  2  s.c o m*/
        zip_base64 = Base64.encodeBase64(FileUtils.readFileToByteArray(zip_file));

    } catch (IOException ex) {
        throw new MojoFailureException("Error!", ex);
    }

    HttpEntity request = MultipartEntityBuilder.create()
            .addBinaryBody("artifact_zip", zip_base64, ContentType.APPLICATION_OCTET_STREAM, "artifact_zip")
            .addTextBody("version", getVersion()).addTextBody("license_id", getLicenseId())
            .addTextBody("git_commit_sha1", getGitCommit())
            .addTextBody("name", getOrganization() + "/" + getRepo()).build();

    HttpPost post = new HttpPost(getSparkpackagesUrl());
    post.setEntity(request);

    post.setHeader("Authorization", getAuthorizationHeader());

    getLog().info("Executing request " + post.getRequestLine());

    // .setProxy(new HttpHost("127.0.0.1", 8888))
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to perform HTTP request", ex);
    }
    getLog().info("Server responded " + response.getStatusLine());

    HttpEntity response_content = response.getEntity();
    if (response_content == null) {
        throw new MojoFailureException("Server responded with an empty response");
    }

    StringBuilder sb = new StringBuilder();
    String line;
    BufferedReader br;
    try {
        br = new BufferedReader(new InputStreamReader(response_content.getContent()));

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException | UnsupportedOperationException ex) {
        throw new MojoFailureException("Could not read response...", ex);
    }
    System.out.println(sb.toString());

    try {
        System.out.println(EntityUtils.toString(response_content));
    } catch (IOException | ParseException ex) {

    }
}

From source file:net.monofraps.gradlecurse.tasks.CurseDeployTask.java

private void uploadArtifact(final Deployment deployment) {
    getLogger().lifecycle("Curse Upload: " + "Uploading to Curse...");
    getLogger().lifecycle("Curse Upload: " + deployment.toString());

    //TODO: binary or app/zip, maybe an option or auto-detect from file extension ?!
    final FileBody fileBody = new FileBody(deployment.getSourceFile(), ContentType.DEFAULT_BINARY,
            deployment.getUploadFileName());

    final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addTextBody("name", deployment.getUploadFileName());
    multipartEntityBuilder.addTextBody("file_type", deployment.getFileType().toString());
    multipartEntityBuilder.addTextBody("change_log", deployment.getChangeLog());
    multipartEntityBuilder.addTextBody("change_markup_type", deployment.getChangeLogMarkup().toString());
    multipartEntityBuilder.addTextBody("known_caveats", deployment.getKnownCaveats());
    multipartEntityBuilder.addTextBody("caveats_markup_type", deployment.getCaveatMarkup().toString());
    multipartEntityBuilder.addPart("file", fileBody);
    multipartEntityBuilder.addTextBody("game_versions", StringUtils.join(deployment.getGameVersions(), ","));

    try {/* w ww  .ja  v  a 2s  . co  m*/
        final HttpPost httpPost = new HttpPost(probeForRedirect(deployment));
        httpPost.addHeader("User-Agent", "GradleCurse Uploader/1.0");
        httpPost.addHeader("X-API-Key", deployment.getApiKey());
        httpPost.setEntity(multipartEntityBuilder.build());

        final HttpClient httpClient = HttpClientBuilder.create().build();
        final HttpResponse httpResponse = httpClient.execute(httpPost);

        getLogger().lifecycle("Curse Upload: " + httpResponse.getStatusLine());
        getLogger().debug(EntityUtils.toString(httpResponse.getEntity()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.msds.km.service.Impl.DrivingLicenseRecognitionServcieiImpl.java

private String recognitionInternal(byte[] b) throws Exception {
    try {/*from  w  ww  .j  a  v  a 2  s. co m*/
        HttpPost httppost = new HttpPost(POST_URL);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addBinaryBody("img", b, ContentType.MULTIPART_FORM_DATA, "test.jpg")
                .addTextBody("action", "driving").addTextBody("callbackurl", "/idcard/").build();

        httppost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            String content = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            return content;
        } catch (IOException e) {
            throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.",
                    e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                throw new Exception(
                        "can not post request to the url:" + POST_URL + ", please check the network.", e);
            }
        }
    } catch (ClientProtocolException e) {
        throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e);
    } catch (IOException e) {
        throw new Exception("can not post request to the url:" + POST_URL + ", please check the network.", e);
    }
}

From source file:net.cazzar.gradle.curseforge.CurseUpload.java

@TaskAction
public void uploadToCurseForge() {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(
            String.format("http://minecraft.curseforge.com/mc-mods/%s/upload-file.json", stub));

    //        System.out.println("VERSION: " + gameVersion);

    post.addHeader("X-API-Key", api_key);
    HttpEntity entity = MultipartEntityBuilder.create().addTextBody("name", artifact_name)
            .addTextBody("game_versions", gameVersion).addTextBody("file_type", String.valueOf(releaseType))
            .addTextBody("change_log", changeLog).addTextBody("change_log_markup_type", changeLogMarkup)
            .addTextBody("known_caveats", caveats).addTextBody("caveats_markup_type", cevatsMarkup)
            .addPart("file", new FileBody(artifact)).build();

    post.setEntity(entity);//from w  ww  .  j a  va 2 s .co m
    try {
        HttpResponse response = client.execute(post);
        HttpEntity ent = response.getEntity();

        if (response.getStatusLine().getStatusCode() == 301) {
            post = new HttpPost(response.getLastHeader("Location").getValue());
            post.addHeader("X-API-Key", api_key);
            post.setEntity(entity);

            EntityUtils.consume(ent);

            response = client.execute(post);
            ent = response.getEntity();
        }

        if (response.getStatusLine().getStatusCode() != 201) {
            Gson gson = new Gson();
            @SuppressWarnings("unchecked")
            Map<String, List<String>> data = gson.fromJson(EntityUtils.toString(ent), Map.class);
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String, List<String>>> iter = data.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, List<String>> entry = iter.next();
                sb.append(entry.getKey()).append(": ").append('\n');//.append(entry.getValue());

                Iterator<String> iter2 = entry.getValue().iterator();
                while (iter2.hasNext()) {
                    sb.append('\t').append(StringEscapeUtils.unescapeHtml(iter2.next()));

                    if (iter2.hasNext())
                        sb.append('\n');
                }

                if (iter.hasNext())
                    sb.append("\n\n");
            }
            throw new RuntimeException(sb.toString());
        }

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

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;/*w  w  w . j a  va  2s  .c om*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:org.wisdom.test.http.MultipartBody.java

/**
 * Computes the request payload.//from  www.  ja  va  2 s .  co m
 *
 * @return the payload containing the declared fields and files.
 */
public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;
                builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                builder.addPart(part.getKey(),
                        new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.lokra.seaweedfs.core.VolumeWrapper.java

/**
 * Upload file.//from ww w.j  a va2  s .  co m
 *
 * @param url         url
 * @param fid         fid
 * @param fileName    fileName
 * @param stream      stream
 * @param ttl         ttl
 * @param contentType contentType
 * @return The size returned is the size stored on SeaweedFS.
 * @throws IOException Http connection is fail or server response within some error message.
 */
long uploadFile(String url, String fid, String fileName, InputStream stream, String ttl,
        ContentType contentType) throws IOException {
    HttpPost request;
    if (ttl != null)
        request = new HttpPost(url + "/" + fid + "?ttl=" + ttl);
    else
        request = new HttpPost(url + "/" + fid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(CharsetUtils.get("UTF-8"));
    builder.addBinaryBody("upload", stream, contentType, fileName);
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    JsonResponse jsonResponse = connection.fetchJsonResultByRequest(request);
    convertResponseStatusToException(jsonResponse.statusCode, url, fid, false, false, false, false);
    return (Integer) objectMapper.readValue(jsonResponse.json, Map.class).get("size");
}

From source file:aiai.ai.station.actors.UploadResourceActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;/* w  w  w. j a  v a 2s  . c o  m*/
    }
    if (!globals.isStationEnabled) {
        return;
    }

    UploadResourceTask task;
    List<UploadResourceTask> repeat = new ArrayList<>();
    while ((task = poll()) != null) {
        boolean isOk = false;
        try (InputStream is = new FileInputStream(task.file)) {
            log.info("Start uploading result data to server, resultDataFile: {}", task.file);

            final String uri = globals.uploadRestUrl + '/' + task.taskId;
            HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setCharset(StandardCharsets.UTF_8)
                    .addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, task.file.getName()).build();

            Request request = Request.Post(uri).connectTimeout(5000).socketTimeout(5000).body(entity);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            String json = response.returnContent().asString();

            UploadResult result = fromJson(json);
            log.info("'\tresult data was successfully uploaded");
            if (!result.isOk) {
                log.error("Error uploading file, server error: " + result.error);
            }
            isOk = result.isOk;
        } catch (HttpResponseException e) {
            log.error("Error uploading code", e);
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e.toString());
        } catch (IOException e) {
            log.error("IOException", e);
        } catch (Throwable th) {
            log.error("Throwable", th);
        }
        if (!isOk) {
            log.error("'\tTask assigned one more time.");
            repeat.add(task);
        }

    }
    for (UploadResourceTask uploadResourceTask : repeat) {
        add(uploadResourceTask);
    }
}

From source file:com.activiti.service.activiti.DeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, "repository/deployments"));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, name)
            .build();/* w ww  .j a  va2 s. com*/
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}