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

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.revo.deployr.client.call.project.ProjectImportCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *///from   w w w . j  a v a  2  s  .  c  o m
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("descr", new StringBody(descr, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectImportCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectImportCall: io exception.", ioex);
    }

    return pResult;
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

public void uninstallBundle(String symbolicName, File f) throws Exception {
    final long bundleId = getBundleId(symbolicName);

    log.info("Uninstalling bundle {} with bundleId {}", symbolicName, bundleId);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("uninstall"));
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH + "/" + bundleId)
            .withCredentials(username, password).withEntity(entity)).assertStatus(200);
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

/** Calls PackageAdmin.refreshPackages to enforce re-wiring of all bundles. */
public void refreshPackages() throws Exception {
    log.info("Refresh packages.");

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("refreshPackages"));

    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH).withCredentials(username, password)
            .withEntity(entity)).assertStatus(200);
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

/** Start specified bundle */
public void startBundle(String symbolicName) throws Exception {
    // To start the bundle we POST action=start to its URL
    final String path = getBundlePath(symbolicName, null);
    log.info("Starting bundle {} via {}", symbolicName, path);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("start"));
    executor.execute(builder.buildPostRequest(path).withCredentials(username, password).withEntity(entity))
            .assertStatus(200);/*  w w w . j a  v  a2s.c o m*/
}

From source file:com.revo.deployr.client.call.project.ProjectWorkspaceUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *///from   w  ww  .  ja v a2s .c om
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("project", new StringBody(this.project, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("name", new StringBody(this.name, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectWorkspaceUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectWorkspaceUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:cn.clxy.upload.ApacheHCUploader.java

private void post(Map<String, ContentBody> params) {

    HttpPost post = new HttpPost(Config.url);
    MultipartEntity entity = new MultipartEntity();
    for (Entry<String, ContentBody> e : params.entrySet()) {
        entity.addPart(e.getKey(), e.getValue());
    }/*from  w  w  w .j a v  a2s  . c o  m*/
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("Upload failed.");
        }
    } catch (Exception e) {
        post.abort();
        throw new RuntimeException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.mobileuni.helpers.FileManager.java

public void UploadToUrl(String siteUrl, String token, String filepath) {

    String url = siteUrl + "/webservice/upload.php?token=" + token;
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url);
    File file = new File(filepath);

    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            MimeTypeMap.getFileExtensionFromUrl(filepath.substring(filepath.lastIndexOf("."))));

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, mimetype);
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);//from   w ww .  ja v  a2  s . c om
    Log.d(TAG, "upload executing request " + httppost.getRequestLine());
    try {

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        Log.d(TAG, "upload line status " + response.getStatusLine());
        if (resEntity != null) {
            Log.d(TAG, "upload " + EntityUtils.toString(resEntity));
            //JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
        } else {
            Log.d(TAG, "upload error: " + EntityUtils.toString(resEntity));
        }

    } catch (Exception ex) {
        Log.d(TAG, "Error: " + ex);
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:cn.clxy.codes.upload.ApacheHCUploader.java

private void post(Map<String, ContentBody> params) {

    HttpPost post = new HttpPost(Config.URL);
    MultipartEntity entity = new MultipartEntity();
    for (Entry<String, ContentBody> e : params.entrySet()) {
        entity.addPart(e.getKey(), e.getValue());
    }//from  www .  j a v  a  2 s.c om
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("Upload failed.");
        }
    } catch (Exception e) {
        post.abort();
        throw new RuntimeException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

/** Install a bundle using the Felix webconsole HTTP interface, with a specific start level */
public void installBundle(File f, boolean startBundle, int startLevel) throws Exception {

    // Setup request for Felix Webconsole bundle install
    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("install"));
    if (startBundle) {
        entity.addPart("bundlestart", new StringBody("true"));
    }//from   w  w  w . ja  va2s .  c o m
    entity.addPart("bundlefile", new FileBody(f));

    if (startLevel > 0) {
        entity.addPart("bundlestartlevel", new StringBody(String.valueOf(startLevel)));
        log.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        log.info("Installing bundle {} at default start level", f.getName());
    }

    // Console returns a 302 on success (and in a POST this
    // is not handled automatically as per HTTP spec)
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH).withCredentials(username, password)
            .withEntity(entity)).assertStatus(302);
}

From source file:com.revo.deployr.client.call.project.ProjectDirectoryUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *//*from   w w w.  j  av a  2 s.c  o m*/
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("project", new StringBody(project, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("filename", new StringBody(options.filename, "text/plain", Charset.forName("UTF-8")));
        if (options.descr != null)
            entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8")));

        entity.addPart("overwrite",
                new StringBody(Boolean.toString(options.overwrite), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectDirectoryUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectDirectoryUploadCall: io exception.", ioex);
    }

    return pResult;
}