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

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

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

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

public void prepareRunnerObject(Object obj) {
    if (obj instanceof MultipartEntityBuilder) {
        MultipartEntityBuilder builder = (MultipartEntityBuilder) obj;
        final File file = new File(externalProcRunner.getInputFilePath(DATAFILENUMBER));
        FileBody fb = new FileBody(file);
        builder.addPart("input.infile_", fb);
        final File file2 = new File(externalProcRunner.getInputFilePath(CONFIGFILENUMBER));
        FileBody fb2 = new FileBody(file2);
        builder.addPart("input.upload_conffile_", fb2);
    }/*from   w ww .ja  v a2s .  c  o  m*/
}

From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java

@Override
protected Void doInBackground(Void... voids) {
    try {/*w ww  .j a  v  a 2  s.  c om*/

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"),
                ContentType.create("Multipart/related", "UTF-8"));
        builder.addPart("image", new FileBody(new File(path)));

        InputStream inputStream = null;
        HttpClient httpClient = AndroidHttpClient.newInstance("Android");

        String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, "");
        String encodeCarNo = "";

        if (false == carNo.equals("")) {
            encodeCarNo = URLEncoder.encode(carNo, "UTF-8");
        }
        HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo);
        httpPost.setEntity(builder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        inputStream.close();

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

From source file:MainFrame.HttpCommunicator.java

public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException {
    String response = null;//from   ww w  .  j  a  va 2s  .c  o  m
    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(jsObj.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();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

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

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.removeLesson", head);

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

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

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);//from   w  w  w  .  j a  va  2s.c o m

    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:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;/*from w  w w .ja  va 2  s .  c  o m*/
    String hashPassword = md5Custom(password);
    JSONObject jsObj = new JSONObject();
    jsObj.put("group", group);
    jsObj.put("newHash", hashPassword);

    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(jsObj.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();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

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

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.updateGroupAccess", head);

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

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpUpload(String url, String dataFieldName, byte[] data, List<NameValuePair> params) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// w ww  . jav a  2s .  c  om
        HttpPost httppost = new HttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody(dataFieldName, data, ContentType.DEFAULT_BINARY, "tempfile");
        for (NameValuePair hp : params) {
            builder.addPart(hp.getName(),
                    new StringBody(hp.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
        }
        HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
        httppost.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(br);
            return je.getAsJsonObject();
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;//from  w ww . j  ava 2 s .  c  o  m
    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:net.ladenthin.snowman.imager.run.uploader.Uploader.java

@Override
public void run() {
    final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager();
    final String url = cs.getSnowmanServer().getApiUrl();
    for (;;) {//from   ww  w.  j a  va 2s . co  m
        File obtainedFile;
        for (;;) {
            if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) {
                LOGGER.trace("killFlag == true");
                return;
            }
            obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile();

            if (obtainedFile == null) {
                Imager.waitALittleBit(300);
                continue;
            } else {
                break;
            }
        }

        boolean doUpload = true;
        while (doUpload) {
            try {
                try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
                    final HttpPost httppost = new HttpPost(url);
                    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM);

                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    builder.addPart(uploadNameCameraimage, fb);
                    builder.addTextBody(uploadNameFilename, obtainedFile.getName());
                    builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername());
                    builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword());
                    builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname());

                    final HttpEntity httpEntity = builder.build();
                    httppost.setEntity(httpEntity);

                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("executing request " + httppost.getRequestLine());
                    }

                    try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("response.getStatusLine(): " + response.getStatusLine());
                        }
                        final HttpEntity resEntity = response.getEntity();
                        if (resEntity != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength());
                            }
                        }
                        final String resString = EntityUtils.toString(resEntity).trim();
                        EntityUtils.consume(resEntity);
                        if (resString.equals(responseSuccess)) {
                            doUpload = false;
                            LOGGER.trace("true: resString.equals(responseSuccess)");
                            LOGGER.trace("resString: {}", resString);
                        } else {
                            LOGGER.warn("false: resString.equals(responseSuccess)");
                            LOGGER.warn("resString: {}", resString);
                            // do not flood log files if an error occurred
                            Imager.waitALittleBit(2000);
                        }
                    }
                }
            } catch (NoHttpResponseException | SocketException e) {
                logIOExceptionAndWait(e);
            } catch (IOException e) {
                LOGGER.warn("Found unknown IOException", e);
            }
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete obtainedFile {}", obtainedFile);
        }
        final boolean delete = obtainedFile.delete();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("delete success {}", delete);
        }
        FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile);
    }
}

From source file:objective.taskboard.it.TemplateIT.java

private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException {
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA);
    StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA);
    builder.addPart("file", fileBody);
    builder.addPart("name", templateName);
    builder.addPart("roles", roles);
    HttpEntity entity = builder.build();

    HttpPost post = new HttpPost();
    post.setURI(new URI("http://localhost:8900/api/templates"));
    post.setHeaders(session);//from   ww  w  . j  a  v a 2 s .c om
    post.setEntity(entity);

    return client.execute(post);
}