Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

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

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:org.opencastproject.remotetest.server.resource.FilesResources.java

public static HttpResponse postFile(TrustedHttpClient client, String mediaPackageID,
        String mediaPackageElementID, String media) throws Exception {
    HttpPost post = new HttpPost(
            getServiceUrl() + "mediapackage/" + mediaPackageElementID + "/" + mediaPackageElementID);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(new File(media)));
    post.setEntity(entity);//from  w  w w .  j a  va  2  s  . c  o m
    return client.execute(post);
}

From source file:mobi.salesforce.client.upload.DemoFileUploader.java

public void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription)
        throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(urlString);
    try {/*from   www.  j av  a 2 s.  co m*/
        // Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("fileDescription",
                new StringBody(fileDescription != null ? fileDescription : ""));
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));

        FileBody fileBody = new FileBody(file, "application/octect-stream");
        // Prepare payload
        multiPartEntity.addPart("attachment", fileBody);

        // Set to request body
        postRequest.setEntity(multiPartEntity);

        // Send request
        HttpResponse response = client.execute(postRequest);

        // Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());
        }
    } catch (Exception ex) {
    }
}

From source file:ADP_Streamline.CURL.java

public void UploadFiles() throws ClientProtocolException, IOException {

    String filePath = "file_path";
    String url = "http://localhost/files";
    File file = new File(filePath);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(file));
    HttpResponse returnResponse = Request.Post(url).body(entity).execute().returnResponse();
    System.out.println("Response status: " + returnResponse.getStatusLine().getStatusCode());
    System.out.println(EntityUtils.toString(returnResponse.getEntity()));
}

From source file:ADP_Streamline.CURL2.java

public String uploadFiles(File file, String siteId, String containerId, String uploadDirectory) {

    String json = null;//from   ww w  .j  a va 2  s.c  om
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    try {

        HttpPost httppost = new HttpPost("/alfresco/service/api/upload?alf_ticket=" + this.ticket);

        FileBody bin = new FileBody(file);
        StringBody siteid = new StringBody(siteId);
        StringBody containerid = new StringBody(containerId);
        StringBody uploaddirectory = new StringBody(uploadDirectory);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("filedata", bin);
        reqEntity.addPart("siteid", siteid);
        reqEntity.addPart("containerid", containerid);
        reqEntity.addPart("uploaddirectory", uploaddirectory);

        httppost.setEntity(reqEntity);

        //log.debug("executing request:" + httppost.getRequestLine());

        HttpResponse response = httpclient.execute(targetHost, httppost);

        HttpEntity resEntity = response.getEntity();

        //log.debug("response status:" + response.getStatusLine());

        if (resEntity != null) {
            //log.debug("response content length:" + resEntity.getContentLength());

            json = EntityUtils.toString(resEntity);
            //log.debug("response content:" + json);
        }

        EntityUtils.consume(resEntity);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return json;
}

From source file:org.wikipedia.vlsergey.secretary.jwpf.actions.Review.java

public Review(boolean bot, Revision revision, String token, String comment, Boolean unapprove,
        Integer flag_accuracy) {//  w  w  w  .j  ava 2s. c  om
    super(bot);

    log.info("[action=review]: " + revision + "; " + token + "; " + comment + "; " + unapprove + "; "
            + flag_accuracy);

    HttpPost postMethod = new HttpPost("/api.php");
    MultipartEntity multipartEntity = new MultipartEntity();
    setMaxLag(multipartEntity);
    setFormatXml(multipartEntity);

    setParameter(multipartEntity, "action", "review");
    setParameter(multipartEntity, "token", token);

    setParameter(multipartEntity, "revid", revision.getId().toString());

    if (comment != null)
        setParameter(multipartEntity, "comment", comment);
    if (unapprove != null)
        setParameter(multipartEntity, "unapprove", "" + unapprove);
    if (flag_accuracy != null)
        setParameter(multipartEntity, "flag_accuracy", "" + flag_accuracy);

    postMethod.setEntity(multipartEntity);
    msgs.add(postMethod);
}

From source file:com.rogiel.httpchannel.http.PostMultipartRequest.java

public PostMultipartRequest(HttpContext ctx, String uri) {
    super(ctx, uri);
    this.entity = new MultipartEntity() {
        @Override/*www. j ava 2s .  c  om*/
        protected String generateBoundary() {
            return "---------------------------9849436581144108930470211272";
        }
    };
}

From source file:nl.igorski.lib.utils.network.HTTPTransfer.java

/**
 * quick wrapper to POST data to a server
 *
 * @param aURL    {String} URL of the server
 * @param aParams {List<NameValuePair>} optional list of parameters to send
        /*from  w w w  .  j a v a  2 s .co m*/
 * @return {HttpResponse}
 */
public static HttpResponse post(String aURL, List<NameValuePair> aParams) {
    HttpPost post = new HttpPost(urlEncode(aURL, null));

    post.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    MultipartEntity entity = new MultipartEntity();

    for (NameValuePair pair : aParams) {
        try {
            entity.addPart(pair.getName(), new StringBodyNoHeaders(pair.getValue()));
        } catch (UnsupportedEncodingException e) {
        }
    }
    post.setEntity(entity);

    HttpResponse out = null;

    try {
        out = getClient().execute(post);
    } catch (Exception e) {
    }

    return out;
}

From source file:com.qcloud.CloudClient.java

public String post(String url, Map<String, String> header, Map<String, Object> body, byte[] data)
        throws UnsupportedEncodingException, IOException {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("accept", "*/*");
    httpPost.setHeader("connection", "Keep-Alive");
    httpPost.setHeader("user-agent", "qcloud-java-sdk");
    if (header != null) {
        for (String key : header.keySet()) {
            httpPost.setHeader(key, header.get(key));
        }/*  w w w  .  j a  v  a  2 s  .c o m*/
    }

    if (false == header.containsKey("Content-Type")
            || header.get("Content-Type").equals("multipart/form-data")) {
        MultipartEntity multipartEntity = new MultipartEntity();
        if (body != null) {
            for (String key : body.keySet()) {
                multipartEntity.addPart(key, new StringBody(body.get(key).toString()));
            }
        }

        if (data != null) {
            ContentBody contentBody = new ByteArrayBody(data, "qcloud");
            multipartEntity.addPart("fileContent", contentBody);
        }
        httpPost.setEntity(multipartEntity);
    } else {
        if (data != null) {
            String strBody = new String(data);
            StringEntity stringEntity = new StringEntity(strBody);
            httpPost.setEntity(stringEntity);
        }
    }

    //        HttpHost proxy = new HttpHost("127.0.0.1",8888);
    //        mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

    HttpResponse httpResponse = mClient.execute(httpPost);
    int code = httpResponse.getStatusLine().getStatusCode();
    return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}

From source file:com.willowtreeapps.uploader.testflight.TestFlightUploader.java

public Map upload(UploadRequest ur) throws IOException, org.json.simple.parser.ParseException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpHost targetHost = new HttpHost(HOST);
    HttpPost httpPost = new HttpPost(POST);
    FileBody fileBody = new FileBody(ur.file);

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("api_token", new StringBody(ur.apiToken));
    entity.addPart("team_token", new StringBody(ur.teamToken));
    entity.addPart("notes", new StringBody(ur.buildNotes));
    entity.addPart("file", fileBody);

    if (ur.dsymFile != null) {
        FileBody dsymFileBody = new FileBody(ur.dsymFile);
        entity.addPart("dsym", dsymFileBody);
    }// w  ww.  j  a v  a 2s  .com

    if (ur.lists.length() > 0) {
        entity.addPart("distribution_lists", new StringBody(ur.lists));
    }

    entity.addPart("notify", new StringBody(ur.notifyTeam ? "True" : "False"));
    entity.addPart("replace", new StringBody(ur.replace ? "True" : "False"));
    httpPost.setEntity(entity);

    return this.send(ur, httpClient, targetHost, httpPost);
}

From source file:uk.ac.diamond.scisoft.feedback.FeedbackRequest.java

/**
 * Method used to submit a form data/file through HTTP to a GAE servlet
 * //w  w  w .  ja  v  a  2  s .  c  o m
 * @param email
 * @param to
 * @param name
 * @param subject
 * @param messageBody
 * @param attachmentFiles
 * @param monitor
 */
public static IStatus doRequest(String email, String to, String name, String subject, String messageBody,
        List<File> attachmentFiles, IProgressMonitor monitor) throws Exception {
    Status status = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    FeedbackProxy.init();
    host = FeedbackProxy.getHost();
    port = FeedbackProxy.getPort();

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    // if there is a proxy
    if (host != null) {
        HttpHost proxy = new HttpHost(host, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    try {
        HttpPost httpost = new HttpPost(SERVLET_URL + SERVLET_NAME);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("name", new StringBody(name));
        entity.addPart("email", new StringBody(email));
        entity.addPart("to", new StringBody(to));
        entity.addPart("subject", new StringBody(subject));
        entity.addPart("message", new StringBody(messageBody));

        // add attachement files to the multipart entity
        for (int i = 0; i < attachmentFiles.size(); i++) {
            if (attachmentFiles.get(i) != null && attachmentFiles.get(i).exists())
                entity.addPart("attachment" + i + ".html", new FileBody(attachmentFiles.get(i)));
        }

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        httpost.setEntity(entity);

        // HttpPost post = new HttpPost("http://dawnsci-feedback.appspot.com/dawnfeedback?name=baha&email=baha@email.com&subject=thisisasubject&message=thisisthemessage");
        HttpResponse response = httpclient.execute(httpost);

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        final String reasonPhrase = response.getStatusLine().getReasonPhrase();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            logger.debug("Status code 200");
            status = new Status(IStatus.OK, "Feedback successfully sent", "Thank you for your contribution");
        } else {
            logger.debug("Feedback email not sent - HTTP response: " + reasonPhrase);
            status = new Status(IStatus.WARNING, "Feedback not sent",
                    "The response from the server is the following:\n" + reasonPhrase
                            + "\nClick on OK to submit your feedback using the online feedback form available at http://dawnsci-feedback.appspot.com/");
        }
        logger.debug("HTTP Response: " + response.getStatusLine());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return status;
}