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:com.gorillalogic.monkeytalk.server.tests.MultipartTest.java

@Test
public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);//w w w  .  j  ava  2s  .  c  o m

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
}

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

/**
 * /*from   w  ww. jav  a 2  s. co m*/
 * @param username
 *            the
 * @param pw
 *            password
 */
protected PostPostLogin(boolean isBot, final TicketData ticketData, String username, final String password) {
    super(isBot);

    log.info("[action=login]: " + username + "; " + ticketData.getToken());

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

    setParameter(multipartEntity, "action", "login");
    setParameter(multipartEntity, "lgname", username);
    setParameter(multipartEntity, "lgpassword", password);
    setParameter(multipartEntity, "lgtoken", ticketData.getToken());

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

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

/**
 * /*  ww  w.  j  a v  a  2  s.  c o  m*/
 * @param username
 *            the
 * @param pw
 *            password
 */
public PostLogin(boolean isBot, final String username, final String password) {
    super(isBot);
    this.username = username;
    this.password = password;

    log.info("[action=login]: " + username);

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

    setParameter(multipartEntity, "action", "login");
    setParameter(multipartEntity, "lgname", username);
    setParameter(multipartEntity, "lgpassword", password);

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

From source file:com.openkm.applet.Util.java

/**
 * Upload scanned document to OpenKM/*from  w  w w  .  jav a  2 s  . c o  m*/
 * 
 */
public static String createDocument(String token, String path, String fileName, String fileType, String url,
        List<BufferedImage> images) throws MalformedURLException, IOException {
    log.info("createDocument(" + token + ", " + path + ", " + fileName + ", " + fileType + ", " + url + ", "
            + images + ")");
    File tmpDir = createTempDir();
    File tmpFile = new File(tmpDir, fileName + "." + fileType);
    ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile);
    String response = "";

    try {
        if ("pdf".equals(fileType)) {
            ImageUtils.writePdf(images, ios);
        } else if ("tif".equals(fileType)) {
            ImageUtils.writeTiff(images, ios);
        } else {
            if (!ImageIO.write(images.get(0), fileType, ios)) {
                throw new IOException("Not appropiated writer found!");
            }
        }

        ios.flush();
        ios.close();

        if (token != null) {
            // Send image
            HttpClient client = new DefaultHttpClient();
            MultipartEntity form = new MultipartEntity();
            form.addPart("file", new FileBody(tmpFile));
            form.addPart("path", new StringBody(path, Charset.forName("UTF-8")));
            form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT
            HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token);
            post.setHeader("Cookie", "jsessionid=" + token);
            post.setEntity(form);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = client.execute(post, responseHandler);
        } else {
            // Store in disk
            String home = System.getProperty("user.home");
            File dst = new File(home, tmpFile.getName());
            copyFile(tmpFile, dst);
            response = "Image copied to " + dst.getPath();
        }
    } finally {
        FileUtils.deleteQuietly(tmpDir);
    }

    log.info("createDocument: " + response);
    return response;
}

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

public static HttpResponse addZippedMediaPackage(TrustedHttpClient client, InputStream mediaPackage)
        throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "addZippedMediaPackage");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("mediaPackage", new InputStreamBody(mediaPackage, "mediapackage.zip"));
    post.setEntity(entity);//from  ww  w  .  j ava  2 s  .  c  o  m
    return client.execute(post);
}

From source file:org.jboss.test.capedwarf.blobstore.support.FileUploader.java

public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents)
        throws URISyntaxException, IOException {
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(uri);
    MultipartEntity entity = new MultipartEntity();
    ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename);
    entity.addPart(partName, contentBody);
    post.setEntity(entity);/*w  w w  .  j  a va2  s  .c om*/

    HttpResponse response = httpClient.execute(post);
    return EntityUtils.toString(response.getEntity());
}

From source file:com.mashape.unirest.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntity entity = new MultipartEntity();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;//from w w  w  .  j  a  va2s  .  c om
                entity.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                try {
                    entity.addPart(part.getKey(),
                            new StringBody(part.getValue().toString(), Charset.forName(UTF_8)));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return entity;
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.dataconservancy.ui.it.support.IngestPackageRequest.java

public HttpPost asHttpPost(String packageMimeType) throws UnsupportedEncodingException {
    if (packageToIngest == null) {
        throw new IllegalStateException(
                "The package to ingest must not be null: call setPackageToIngest(File) " + "first");
    }/*from www. j  a  v  a 2s . co m*/

    final HttpPost request = new HttpPost(urlConfig.getIngestPackageUrl().toString());
    //
    //
    //        if (packageMimeType != null) {
    //            request.setHeader(HttpHeaders.CONTENT_TYPE, packageMimeType);
    //        }
    //
    //        request.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(packageToIngest.length()));

    final MultipartEntity multiPart = new MultipartEntity();

    final FileBody fileBody;

    if (packageMimeType != null) {
        fileBody = new FileBody(packageToIngest, packageMimeType);
    } else {
        fileBody = new FileBody(packageToIngest);
    }

    multiPart.addPart("uploadedFile", fileBody);
    multiPart.addPart(INGEST_STRIPES_EVENT, new StringBody("Ingest", Charset.forName("UTF-8")));

    request.setEntity(multiPart);

    return request;

}

From source file:com.phunkosis.gifstitch.helpers.ShareHelper.java

public static String uploadToSite(String filePath, Context c) {
    URLStorageHelper storage = new URLStorageHelper(c);
    String url = storage.lookupUrl(filePath);
    if (url != null) {
        return url;
    }/*from ww w . j  a v  a 2 s  .  co  m*/

    String did = GSSettings.getDeviceId();
    File file = new File(filePath);
    String seed = "" + GSS + did + file.getName();
    String hash = generateSHA256(seed);

    HttpClient httpClient = new DefaultHttpClient();

    try {
        HttpPost httpPost = new HttpPost(SHAREURL);
        FileBody fileBody = new FileBody(file);
        StringBody didBody = new StringBody(did);
        StringBody hashBody = new StringBody(hash);
        StringBody filenameBody = new StringBody(file.getName());

        MultipartEntity mpe = new MultipartEntity();
        mpe.addPart("did", didBody);
        mpe.addPart("hash", hashBody);
        mpe.addPart("img", filenameBody);
        mpe.addPart("sharedgif", fileBody);

        httpPost.setEntity(mpe);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            BufferedReader r = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line = r.readLine();

            if (line != null && line.startsWith("http:")) {
                storage.addRow(filePath, line);
                return line;
            }

            return line;
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            httpClient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
    return null;
}

From source file:org.ubicompforall.BusTUC.Speech.HTTP.java

public void sendPostByteArray(byte[] buf) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst");

    try {/*ww w.jav  a 2  s  . c o m*/

        MultipartEntity entity = new MultipartEntity();
        // entity.addPart("speechinput", new FileBody((buf,
        // "application/zip"));
        entity.addPart("speechinput", new ByteArrayBody(buf, "Jun.wav"));

        httppost.setEntity(entity);
        String response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8");
        System.out.println("RESPONSE: " + response);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
}