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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:MainFrame.HttpCommunicator.java

public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException {
    String response = null;/*  www  .  j a  v a2  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(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:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;//from w  w  w  .j a  v a  2 s.  com
    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:cc.sferalabs.libs.telegram.bot.api.TelegramBot.java

/**
 * Sends a request to the server.//from  ww  w .  ja v  a 2 s.com
 * 
 * @param <T>
 *            the class to cast the returned value to
 * @param request
 *            the request to be sent
 * @param timeout
 *            the read timeout value (in milliseconds) to be used for server
 *            response. A timeout of zero is interpreted as an infinite
 *            timeout
 * @return the JSON object representing the value of the field "result" of
 *         the response JSON object cast to the specified type parameter
 * @throws ResponseError
 *             if the server returned an error response, i.e. the value of
 *             the field "ok" of the response JSON object is {@code false}
 * @throws ParseException
 *             if an error occurs while parsing the server response
 * @throws IOException
 *             if an I/O exception occurs
 */
@SuppressWarnings("unchecked")
public <T> T sendRequest(Request request, int timeout) throws IOException, ParseException, ResponseError {
    HttpURLConnection connection = null;
    try {
        URL url = buildUrl(request);
        log.debug("Performing request: {}", url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(timeout);

        if (request instanceof SendFileRequest) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            Path filePath = ((SendFileRequest) request).getFilePath();
            builder.addBinaryBody(((SendFileRequest) request).getFileParamName(), filePath.toFile());
            HttpEntity multipart = builder.build();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", multipart.getContentType().getValue());
            connection.setRequestProperty("Content-Length", "" + multipart.getContentLength());

            try (OutputStream out = connection.getOutputStream()) {
                multipart.writeTo(out);
            }
        } else {
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Length", "0");
        }

        boolean httpOk = connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        try (InputStream in = httpOk ? connection.getInputStream() : connection.getErrorStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            JSONObject resp = (JSONObject) parser.parse(br);
            log.debug("Response: {}", resp);

            boolean ok = (boolean) resp.get("ok");
            if (!ok) {
                String description = (String) resp.get("description");
                if (description == null) {
                    description = "ok=false";
                }
                throw new ResponseError(description);
            }
            return (T) resp.get("result");
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.wisdom.framework.vertx.FormTest.java

@Test
public void testFormSubmissionAsMultipart() throws InterruptedException, IOException {
    Router router = prepareServer();//from   www .  jav  a  2  s.  c  o m

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result submit() {
            final Map<String, List<String>> form = context().form();
            // String
            if (!form.get("key").get(0).equals("value")) {
                return badRequest("key is not equals to value");
            }

            // Multiple values
            List<String> list = form.get("list");
            if (!(list.contains("1") && list.contains("2"))) {
                return badRequest("list does not contains 1 and 2");
            }

            return ok(context().header(HeaderNames.CONTENT_TYPE));
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "submit");
    when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class)))
            .thenReturn(route);

    server.start();
    waitForStart(server);

    int port = server.httpPort();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("key", "value", ContentType.TEXT_PLAIN).addTextBody("list", "1", ContentType.TEXT_PLAIN)
            .addTextBody("list", "2", ContentType.TEXT_PLAIN);

    final HttpResponse response = Request.Post("http://localhost:" + port + "/").body(builder.build()).execute()
            .returnResponse();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.MULTIPART);
}

From source file:org.duracloud.common.web.RestHttpHelperTest.java

@Test
public void testMultipartPost() throws Exception {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("text-part", "text");
    // Note: Including a file as one piece of the multipart body
    // causes this test to fail intermittently. Replacing it here with string bytes.
    builder.addBinaryBody("binary-part", "binary-content".getBytes());
    HttpEntity reqEntity = builder.build();

    HttpResponse response = helper.multipartPost(getUrl(), reqEntity);
    verifyResponse(response);//from  ww  w. j  av a 2  s .  co  m
}

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  v  a 2  s.  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:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testSubmit() throws Exception {
    String schedulerUrl = getResourceUrl("submit");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);/* w  ww. j  a v a  2 s  .  c o m*/
    File jobFile = RestFuncTHelper.getDefaultJobXmlfile();
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("file",
            new FileBody(jobFile, ContentType.APPLICATION_XML));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    JSONObject jsonObj = toJsonObject(response);
    assertNotNull(jsonObj.get("id").toString());
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testUrlMatrixParamsShouldReplaceJobVariables() throws Exception {
    File jobFile = new File(RestSchedulerJobTaskTest.class.getResource("config/job_matrix_params.xml").toURI());

    String schedulerUrl = getResourceUrl("submit;var=matrix_param_val");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);//from  w  w w  .  j  av a2s .  co m

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("file",
            new FileBody(jobFile, ContentType.APPLICATION_XML));
    httpPost.setEntity(multipartEntityBuilder.build());

    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    JSONObject jsonObj = toJsonObject(response);
    final String jobId = jsonObj.get("id").toString();
    assertNotNull(jobId);

    waitJobState(jobId, JobStatus.FINISHED, TimeUnit.MINUTES.toMillis(1));
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadVideoRequest.java

/**
 * Create the required multipart entity//from w  w  w  .  j  a v  a2s  .  co m
 * @param uploadId Session ID
 * @return Entity to submit to the upload
 * @throws ClientProtocolException
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("media_type", "2");
    builder.setBoundary(api.getUuid());

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

From source file:com.norconex.committer.gsa.GsaCommitter.java

@Override
protected void commitBatch(List<ICommitOperation> batch) {

    File xmlFile = null;//from  w  w  w .  j a  v  a  2  s . co  m
    try {
        xmlFile = File.createTempFile("batch", ".xml");
        FileOutputStream fout = new FileOutputStream(xmlFile);
        XmlOutput xmlOutput = new XmlOutput(fout);
        Map<String, Integer> stats = xmlOutput.write(batch);
        fout.close();

        HttpPost post = new HttpPost(feedUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("data", xmlFile, ContentType.APPLICATION_XML, xmlFile.getName());
        builder.addTextBody("datasource", "GSA_Commiter");
        builder.addTextBody("feedtype", "full");

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(post);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new CommitterException("Invalid response to Committer HTTP request. " + "Response code: "
                    + status.getStatusCode() + ". Response Message: " + status.getReasonPhrase());
        }
        LOG.info("Sent " + stats.get("docAdded") + " additions and " + stats.get("docRemoved")
                + " removals to GSA");

    } catch (Exception e) {
        throw new CommitterException("Cannot index document batch to GSA.", e);
    } finally {
        FileUtils.deleteQuietly(xmlFile);
    }
}