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

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

Introduction

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

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:net.yama.android.managers.connection.OAuthConnectionManager.java

/**
 * Special request for photo upload since OAuth doesn't handle multipart/form-data
 *///from  ww  w. ja  va 2  s .  co  m
public String uploadPhoto(WritePhotoRequest request) throws ApplicationException {

    String responseString = null;
    try {
        OAuthAccessor accessor = new OAuthAccessor(OAuthConnectionManager.consumer);
        accessor.accessToken = ConfigurationManager.instance.getAccessToken();
        accessor.tokenSecret = ConfigurationManager.instance.getAccessTokenSecret();

        String tempImagePath = request.getParameterMap().remove(Constants.TEMP_IMAGE_FILE_PATH);
        String eventId = request.getParameterMap().remove(Constants.EVENT_ID_KEY);

        ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>();
        convertRequestParamsToOAuth(params, request.getParameterMap());
        OAuthMessage message = new OAuthMessage(request.getMethod(), request.getRequestURL(), params);
        message.addRequiredParameters(accessor);
        List<Map.Entry<String, String>> oAuthParams = message.getParameters();
        String url = OAuth.addParameters(request.getRequestURL(), oAuthParams);

        HttpPost post = new HttpPost(url);
        File photoFile = new File(tempImagePath);
        FileBody photoContentBody = new FileBody(photoFile);
        StringBody eventIdBody = new StringBody(eventId);

        HttpClient client = new DefaultHttpClient();
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        reqEntity.addPart(Constants.PHOTO, photoContentBody);
        reqEntity.addPart(Constants.EVENT_ID_KEY, eventIdBody);
        post.setEntity(reqEntity);

        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        responseString = EntityUtils.toString(resEntity);

    } catch (Exception e) {
        Log.e("OAuthConnectionManager", "Exception in uploadPhoto()", e);
        throw new ApplicationException(e);
    }

    return responseString;
}

From source file:org.anon.smart.smcore.test.channel.upload.TestUploadEvent.java

private void uploadFile(String file) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:9020" + "/errortenant/ErrorCases/UploadEvent");

    FileBody bin = new FileBody(new File(file));

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("bin", bin);

    httppost.setEntity(reqEntity);//from  w ww.ja va 2  s.c  om

    System.out.println("executing request " + httppost.getRequestLine());
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String response = null;
    try {
        response = httpclient.execute(httppost, responseHandler);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
}

From source file:mesquite.zephyr.RAxMLRunnerCIPRes.RAxMLRunnerCIPRes.java

public void prepareRunnerObject(Object obj) {
    if (obj instanceof MultipartEntityBuilder) {
        MultipartEntityBuilder builder = (MultipartEntityBuilder) obj;
        final File file = new File(externalProcRunner.getInputFilePath(DATAFILENUMBER));
        FileBody fb = new FileBody(file);
        builder.addPart("input.infile_", fb);
    }/* ww  w  . j  a v a2 s.co m*/
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUploadWithEagerParsing() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {/*from  www .java2s  .  co m*/

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(
                new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:br.itecbrazil.serviceftpcliente.model.ThreadEnvio.java

private void enviarArquivo(File arquivo, Config config) {
    if (gravarBackup(arquivo)) {
        logger.info("Enviando arquivo " + arquivo.getName() + ". Thread: " + Thread.currentThread().getName());
        try {//w ww.  j a va  2  s  . c  o m
            HttpClient httpclient = new org.apache.http.impl.client.DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://" + config.getHost() + "/upload");
            httppost.setHeader("X-Requested-With", "XMLHttpRequest");

            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("id", new StringBody(config.getUsuario()));
            mpEntity.addPart("arquivo", new FileBody(arquivo));

            httppost.setEntity(mpEntity);
            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == 200) {
                logger.info("Arquivo arquivo " + arquivo.getName() + " enviado com sucesso. Thread: "
                        + Thread.currentThread().getName());
                atualizarDadoDeEnvio(arquivo);
                arquivo.delete();
                logger.info("Arquivo deletado " + arquivo.getName() + " do diretorio de envio. Thread: "
                        + Thread.currentThread().getName());
            }

        } catch (MalformedURLException ex) {
            loggerExceptionEnvio.info(ex);
        } catch (IOException ex) {
            loggerExceptionEnvio.info(ex);
        }
    }
}

From source file:com.brightcove.com.uploader.helper.MediaManagerHelper.java

public Long uploadFile(URI uri, File f, DefaultHttpClient client)
        throws HttpException, IOException, URISyntaxException, ParserConfigurationException, SAXException {
    mLog.info("using " + uri.getHost() + " on port " + uri.getPort() + " for MM upload");

    HttpPost method = new HttpPost(uri);
    MultipartEntity entityIn = new MultipartEntity();
    entityIn.addPart("FileName", new StringBody(f.getName(), Charset.forName("UTF-8")));

    FileBody fileBody = null;/*  w  w  w .j  a v a2s  . c  om*/

    if (f != null) {
        fileBody = new FileBody(f);
    }

    if (f != null) {
        entityIn.addPart(f.getName(), fileBody);
    }

    entityIn.addPart("Upload", new StringBody("Submit Query", Charset.forName("UTF-8")));
    method.setEntity(entityIn);

    if (client != null) {
        return executeUpload(method, client);
    }

    return null;
}

From source file:net.idea.opentox.cli.dataset.DatasetClient.java

@Override
protected HttpEntity createPOSTEntity(Dataset dataset, List<POLICY_RULE> accessRights)
        throws InvalidInputException, Exception {
    if (dataset.getInputData() == null || dataset.getInputData().getInputFile() == null)
        throw new InvalidInputException("File to import not defined!");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);

    entity.addPart(_WEBFORM.title.name(), new StringBody(dataset.getMetadata().getTitle(), utf8));
    entity.addPart(_WEBFORM.seeAlso.name(), new StringBody(dataset.getMetadata().getSeeAlso(), utf8));
    entity.addPart(_WEBFORM.license.name(),
            new StringBody(dataset.getMetadata().getRights() == null ? ""
                    : (dataset.getMetadata().getRights().getURI() == null ? ""
                            : dataset.getMetadata().getRights().getURI()),
                    utf8));//from ww  w .ja va2 s. c o  m
    entity.addPart(_WEBFORM.match.name(),
            new StringBody(dataset.getInputData().getImportMatchMode().name(), utf8));
    entity.addPart(_WEBFORM.file.name(), new FileBody(dataset.getInputData().getInputFile()));

    return entity;
}

From source file:ninja.utils.NinjaTestBrowser.java

public String uploadFile(String url, String paramName, File fileToUpload) {

    String response = null;/*  www. java 2 s.  c  om*/

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost post = new HttpPost(url);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        entity.addPart(paramName, new FileBody((File) fileToUpload));

        post.setEntity(entity);

        // Here we go!
        response = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        post.releaseConnection();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return response;

}

From source file:com.shmsoft.dmass.lotus.NSFParser.java

private boolean submitProcessing(String url, String taskId, String nsfFile) {
    File file = new File(nsfFile);

    HttpClient httpClient = new DefaultHttpClient();

    try {//from   www .  j a  v  a2 s .  c  om
        HttpPost post = new HttpPost(url + "/submit-processing.html");

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", new FileBody(file));

        entity.addPart("taskId", new StringBody(taskId));

        post.setEntity(entity);

        HttpResponse response = httpClient.execute(post);
        getResponseMessage(response);
    } catch (Exception e) {
        System.out.println("NSFParser -- Problem sending data: " + e.getMessage());

        return false;
    }

    return true;
}

From source file:com.ecocitizen.common.HttpHelper.java

public boolean sendUploadFile(File file) {
    String url = SENSORMAP_UPLOADFILE_URL;
    if (D)/*from w w  w .java2s  .co  m*/
        Log.d(TAG, url);

    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    request.setHeader("User-Agent", HTTP_USER_AGENT);
    MultipartEntity entity = new MultipartEntity();
    ContentBody contentBody = new FileBody(file);
    FormBodyPart bodyPart = new FormBodyPart("file", contentBody);
    entity.addPart(bodyPart);
    request.setEntity(entity);

    try {
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HTTP_STATUS_OK) {
            mLastStatus = Status.SUCCESS;
            return true;
        }
    } catch (ClientProtocolException e) {
        mLastStatus = Status.EXCEPTION;
        e.printStackTrace();
        Log.e(TAG, "Exception in sendUploadFile");
    } catch (IOException e) {
        mLastStatus = Status.EXCEPTION;
        e.printStackTrace();
        Log.e(TAG, "Exception in sendUploadFile");
    }

    return false;
}