Example usage for org.apache.http.entity.mime.content StringBody StringBody

List of usage examples for org.apache.http.entity.mime.content StringBody StringBody

Introduction

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

Prototype

public StringBody(final String text) throws UnsupportedEncodingException 

Source Link

Usage

From source file:de.uzk.hki.da.webservice.HttpFileTransmissionClient.java

/**
 * Post file./*  w  ww. ja  va  2  s. co  m*/
 *
 * @param file the file
 * @param toFile the to file
 */
@SuppressWarnings("finally")
public File postFileAndReadResponse(File file, File toFile) {
    HttpClient httpclient = null;
    ;
    try {
        if (!file.exists()) {
            throw new RuntimeException("Source File does not exist " + file.getAbsolutePath());
        }
        if (url.isEmpty()) {
            throw new RuntimeException("Webservice called but Url is empty");
        }

        httpclient = new DefaultHttpClient();
        logger.info("starting new http client for url " + url);
        HttpPost httppost = new HttpPost(url);
        HttpParams httpRequestParameters = httppost.getParams();
        httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httppost.setParams(httpRequestParameters);

        MultipartEntity multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("fileDescription", new StringBody("doxc Converison"));
        multiPartEntity.addPart("fileName", new StringBody(file.getName()));
        if (sourceMimeType.isEmpty())
            sourceMimeType = "application/octet-stream";
        if (destMimeType.isEmpty())
            destMimeType = "application/octet-stream";
        FileBody fileBody = new FileBody(file, sourceMimeType);
        multiPartEntity.addPart("attachment", fileBody);

        httppost.setEntity(multiPartEntity);

        logger.debug("calling webservice now. recieving response");
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200 && resEntity.getContentType().getValue().startsWith(destMimeType)) {
            InputStream in = resEntity.getContent();

            FileOutputStream fos = new FileOutputStream(toFile);

            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            logger.debug("successfully stored recieved content to " + toFile.getAbsolutePath());
            in.close();
            fos.close();
            cleanup();
        } else {
            logger.error(
                    "Recieved reponse of " + resEntity.getContentType() + ", but expected " + destMimeType);
            printResponse(resEntity);
        }
    } catch (Exception e) {
        logger.error("Exception occured in remotefileTransmission " + e.getStackTrace());
        throw new RuntimeException("Webservice error " + url, e);
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
        return toFile;
    }
}

From source file:uk.co.jarofgreen.cityoutdoors.API.BaseCall.java

protected void addDataToCall(String key, Float value) {
    if (value != null) {
        try {//from www  .j  a  v a  2 s . c  o  m
            multipartEntity.addPart(key, new StringBody(Float.toString(value)));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.ccghe.utils.Server.java

public static void UploadFile(String path, FileTransmitter transmitter) {
    MultipartEntity entity = new MultipartEntity();
    try {/*from  w  w  w.j a va2s  .co  m*/
        entity.addPart("usr", new StringBody(user));
        entity.addPart("pwd", new StringBody(password));
        entity.addPart("cmd", new StringBody(CMD_UPLOAD_FILE));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    new UploadOneFile(path, serverURL, transmitter, entity);
}

From source file:net.asplode.tumblr.Post.java

/**
 * @param email//from   ww  w  .ja  v a 2s.  com
 *            Email address
 * @param password
 *            Password
 * @throws UnsupportedEncodingException
 */
public void setCredentials(String email, String password) throws UnsupportedEncodingException {
    this.email = email;
    this.password = password;
    entity.addPart("email", new StringBody(email));
    entity.addPart("password", new StringBody(password));
}

From source file:com.rackspace.api.clients.veracode.DefaultVeracodeApiClient.java

private String uploadFile(File file, int buildVersion, String appId, String platfrom)
        throws VeracodeApiException {
    HttpPost post = new HttpPost(baseUri.resolve(UPLOAD));

    MultipartEntity entity = new MultipartEntity();

    try {//from  www .  j av  a 2  s  . c  o  m
        entity.addPart(new FormBodyPart("app_id", new StringBody(appId)));
        entity.addPart(new FormBodyPart("version", new StringBody(String.valueOf(buildVersion))));
        entity.addPart(new FormBodyPart("platform", new StringBody(platfrom)));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("The Request could not be made due to an encoding issue", e);

    }

    entity.addPart("file", new FileBody(file, "text/plain"));

    post.setEntity(entity);

    logger.println("Executing Request: " + post.getRequestLine());

    UploadResponse uploadResponse = null;

    try {
        uploadResponse = new UploadResponse(client.execute(post));
    } catch (IOException e) {
        throw new VeracodeApiException("The call to Veracode failed.", e);
    }

    return uploadResponse.getBuildId(buildVersion);
}

From source file:com.glodon.paas.document.api.FileRestAPITest.java

@Test
public void uploadFolderForMultiPart() throws IOException {
    File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null);
    java.io.File file = new ClassPathResource("file/testupload.file").getFile();
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    FileBody fileBody = new FileBody(file);
    StringBody sbId = new StringBody(parentFile.getId());
    StringBody sbSize = new StringBody(String.valueOf(file.length()));
    StringBody sbName = new StringBody("aa/" + file.getName());
    StringBody sbPosition = new StringBody("0");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("fileId", sbId);
    entity.addPart("size", sbSize);
    entity.addPart("fileName", sbName);
    entity.addPart("position", sbPosition);
    entity.addPart("file", fileBody);
    post.setEntity(entity);/*from  w w  w  .  j av  a  2s.  co  m*/

    File uploadFile = getFile(simpleCall(post), null);
    assertEquals(file.getName(), uploadFile.getFullName());
    assertFalse(uploadFile.isFolder());
    File aaFolder = getFile(simpleCall(createGet("/file/1/aa?meta")), "meta");
    assertEquals(aaFolder.getId(), uploadFile.getParentId());
}

From source file:org.sonar.plugins.web.markup.validation.MarkupValidator.java

/**
 * Post contents of HTML file to the W3C validation service. In return, receive a Soap response message.
 *
 * @see http://validator.w3.org/docs/api.html
 *//*from  w  w  w.  j ava  2 s .  com*/
private void postHtmlContents(InputFile inputfile) {

    HttpPost post = new HttpPost(validationUrl);
    HttpResponse response = null;

    post.addHeader("User-Agent", "sonar-w3c-markup-validation-plugin/1.0");

    try {

        LOG.info("W3C Validate: " + inputfile.getRelativePath());

        // file upload
        MultipartEntity multiPartRequestEntity = new MultipartEntity();
        String charset = CharsetDetector.detect(inputfile.getFile());
        FileBody fileBody = new FileBody(inputfile.getFile(), TEXT_HTML_CONTENT_TYPE, charset);
        multiPartRequestEntity.addPart(UPLOADED_FILE, fileBody);

        // set output format
        multiPartRequestEntity.addPart(OUTPUT, new StringBody(SOAP12));

        post.setEntity(multiPartRequestEntity);
        response = executePostMethod(post);

        // write response to report file
        if (response != null) {
            writeResponse(response, inputfile);
        }

    } catch (UnsupportedEncodingException e) {
        LOG.error(e);
    } finally {
        // release any connection resources used by the method
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException ioe) {
                LOG.debug(ioe);
            }
        }
    }
}

From source file:edu.scripps.fl.pubchem.web.session.WebSessionBase.java

protected MultipartEntity addParts(MultipartEntity entity, Object... pairs)
        throws UnsupportedEncodingException {
    for (int ii = 0; ii < pairs.length; ii += 2)
        entity.addPart(pairs[ii].toString(), new StringBody(pairs[ii + 1].toString()));
    return entity;
}

From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java

public void post(final String url, final String fileKey, final File file, final String contentType,
        final Map<String, String> params, final FileUploadCallback callback) {

    if (null == callback) {
        throw new RuntimeException("FileUploadCallback should not be null.");
    }//w  ww  .  j  av a 2s .  com

    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(new Runnable() {
        public void run() {
            try {
                HttpPost httpPost = new HttpPost(url);

                FileBody fileBody;
                if (null == contentType) {
                    fileBody = new FileBody(file);
                } else {
                    fileBody = new FileBody(file, contentType);
                }

                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                if (null == fileKey) {
                    entity.addPart(DEFAULT_FILE_KEY, fileBody);
                } else {
                    entity.addPart(fileKey, fileBody);
                }

                if (null != params) {
                    for (Map.Entry<String, String> e : params.entrySet()) {
                        entity.addPart(e.getKey(), new StringBody(e.getValue()));
                    }
                }

                httpPost.setEntity(entity);

                upload(httpPost, callback);
            } catch (UnsupportedEncodingException e) {
                callback.onFailure(-1, null, e);
            }
        }
    });
}

From source file:com.glodon.paas.document.api.PerformanceRestAPITest.java

/**
 *  multipart/*from  www .  j a  v a2s .  c  o  m*/
 */
@Test
public void testUploadFileForMultiPart() throws IOException {
    File parentFile = createFile("testUpload");
    java.io.File file = new java.io.File("src/test/resources/file/testupload.file");
    if (!file.exists()) {
        file = new java.io.File(tempUploadFile);
    }
    String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    FileBody fileBody = new FileBody(file);
    StringBody sbId = new StringBody(parentFile.getId());
    StringBody sbSize = new StringBody(String.valueOf(file.length()));
    StringBody sbName = new StringBody(file.getName());
    StringBody sbPosition = new StringBody("0");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("fileId", sbId);
    entity.addPart("size", sbSize);
    entity.addPart("fileName", sbName);
    entity.addPart("position", sbPosition);
    entity.addPart("file", fileBody);
    post.setEntity(entity);
    String response = simpleCall(post);
    assertNotNull(response);
    File resultFile = convertString2Obj(response, new TypeReference<File>() {
    });
    assertEquals(file.getName(), resultFile.getFullName());
    assertTrue(file.length() == resultFile.getSize());
}