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:org.dataconservancy.ui.it.support.ValidatingMetadataFileRequest.java

public HttpPost asHttpPost() {
    if (fileToTest == null) {
        throw new IllegalStateException("File not set: call setFileToTest(File) first");
    }//ww w  .j ava2s .  c  o m

    String validatingMetadataFileUrl = urlConfig.getAdminValidatingMetadataFilePathPostUrl().toString();
    HttpPost post = new HttpPost(validatingMetadataFileUrl);
    MultipartEntity entity = new MultipartEntity();
    try {
        entity.addPart(STRIPES_EVENT, new StringBody("Validate", Charset.forName("UTF-8")));
        entity.addPart("metadataFormatId", new StringBody(formatId, Charset.forName("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    FileBody fileBody = new FileBody(fileToTest);
    entity.addPart("sampleMetadataFile", fileBody);
    post.setEntity(entity);

    return post;
}

From source file:ADP_Streamline.CURL2.java

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

    String json = null;//from w ww .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:com.ibm.watson.developer_cloud.visual_insights.v1.VisualInsights.java

/**
 * Upload a set of images as a zip file for visual insight extraction.
 *
 * @param imagesFile the images File// ww w.  j  a v a2  s.c o m
 * @return the Summary of the collection's visual attributes
 */
public Summary getSummary(final File imagesFile) {
    if (imagesFile == null || !imagesFile.exists())
        throw new IllegalArgumentException("imagesFile can not be null or empty");

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart(FILE, new FileBody(imagesFile));
    Request request = Request.Post(SUMMARY_PATH).withEntity(reqEntity);

    return executeRequest(request, Summary.class);

}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.integration.ITScriptConsolePlugin.java

private void execute(ContentBody code) throws Exception {
    RequestBuilder rb = new RequestBuilder(ServerConfiguration.getServerUrl());

    final MultipartEntity entity = new MultipartEntity();
    // Add Sling POST options
    entity.addPart("lang", new StringBody("groovy"));
    entity.addPart("code", code);
    executor.execute(/*from ww  w  . ja  v  a  2 s .  co  m*/
            rb.buildPostRequest("/system/console/sc").withEntity(entity).withCredentials("admin", "admin"))
            .assertStatus(200);
}

From source file:com.dss886.nForumSDK.service.AttachmentService.java

/**
 * /*from   ww w . j ava 2  s.c  o m*/
* ??idid????
* @param boardName ????
* @param file 
* @return /?
* @throws JSONException
* @throws NForumException
* @throws IOException
*/
public Attachment addAttachment(String boardName, File file, ParamOption params)
        throws JSONException, NForumException, IOException {
    String url = host + "attachment/" + boardName + "/add";
    if (params.getParams().containsKey("id")) {
        url = url + "/" + params.getParams().get("id") + returnFormat + appkey;
    } else {
        url = url + returnFormat + appkey;
    }
    FileBody fileBody = new FileBody(file);
    MultipartEntity mEntity = new MultipartEntity();
    mEntity.addPart("file", fileBody);
    PostMethod postMethod = new PostMethod(httpClient, auth, url, mEntity);
    return Attachment.parse(postMethod.postJSON());
}

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException,
        JSONException {//ww  w.  java2  s.com
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}

From source file:org.opencastproject.remotetest.server.IngestRestEndpointTest.java

@Test
public void testUploadClient() throws Exception {
    InputStream is = getClass().getResourceAsStream("/mp-test.zip");
    InputStreamBody fileContent = new InputStreamBody(is, "mp-test.zip");

    // create emptiy MediaPackage
    HttpPost postStart = new HttpPost(BASE_URL + "/ingest/addZippedMediaPackage");

    MultipartEntity mpEntity = new MultipartEntity();
    mpEntity.addPart("workflowDefinitionId", new StringBody("full"));
    mpEntity.addPart("userfile", fileContent);
    postStart.setEntity(mpEntity);/*from ww w  .  j ava  2 s  . c  o m*/

    HttpResponse response = client.execute(postStart);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:de.xwic.appkit.core.file.impl.hbn.RemoteFileAccessClient.java

@Override
protected int storeFile(final File file) throws IOException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart(PARAM_ACTION, new StringBody(ACTION_FILE_HANDLE));
    multipartEntity.addPart(PARAM_FH_ACTION, new StringBody(PARAM_FH_ACTION_UPLOAD));
    multipartEntity.addPart(PARAM_FH_STREAM, new FileBody(file));
    return URemoteAccessClient.multipartRequestInt(multipartEntity, config);
}

From source file:org.deviceconnect.android.manager.test.MultipartTest.java

/**
 * POST????????./*from www .  ja  v a  2  s  . c  o m*/
 */
public void testParsingMutilpartAsRequestParametersMethodPost() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(NotificationProfileConstants.PROFILE_NAME);
    builder.setAttribute(NotificationProfileConstants.ATTRIBUTE_NOTIFY);
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(DConnectProfileConstants.PARAM_DEVICE_ID, new StringBody(getDeviceId()));
        entity.addPart(NotificationProfileConstants.PARAM_TYPE, new StringBody("0"));
        entity.addPart(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, new StringBody(getAccessToken()));
        HttpPost request = new HttpPost(builder.toString());
        request.setEntity(entity);
        JSONObject response = sendRequest(request);
        assertResultOK(response);
    } catch (UnsupportedEncodingException e) {
        fail(e.getMessage());
    } catch (JSONException e) {
        fail(e.getMessage());
    }
}

From source file:org.deviceconnect.android.manager.test.MultipartTest.java

/**
 * PUT????????.//from   w ww.  ja  v  a 2 s  . c  om
 */
public void testParsingMutilpartAsRequestParametersMethodPut() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(DeviceOrientationProfileConstants.PROFILE_NAME);
    builder.setAttribute(DeviceOrientationProfileConstants.ATTRIBUTE_ON_DEVICE_ORIENTATION);
    try {
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(DConnectProfileConstants.PARAM_DEVICE_ID, new StringBody(getDeviceId()));
        entity.addPart(DConnectProfileConstants.PARAM_SESSION_KEY, new StringBody(getClientId()));
        entity.addPart(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, new StringBody(getAccessToken()));
        HttpPut request = new HttpPut(builder.toString());
        request.setEntity(entity);
        JSONObject response = sendRequest(request);
        assertResultOK(response);
    } catch (UnsupportedEncodingException e) {
        fail(e.getMessage());
    } catch (JSONException e) {
        fail(e.getMessage());
    }
}