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:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.//from ww  w  .  j a  v a2 s  .c o  m
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:Technique.PostFile.java

public static void upload(String files) throws Exception {

    String userHome = System.getProperty("user.home");
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("http://localhost/image/up.php");
    File file = new File(files);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody contentFile = new FileBody(file);
    mpEntity.addPart("userfile", contentFile);
    httppost.setEntity(mpEntity);/*from  w  w  w.  j  a  v  a2s . c  om*/
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")) {
        // Successfully Uploaded
    } else {
        // Did not upload. Add your logic here. Maybe you want to retry.
    }
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}

From source file:org.eclipse.cbi.common.signing.Signer.java

public static void signFile(File source, File target, String signerUrl)
        throws IOException, MojoExecutionException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(signerUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("file", new FileBody(source));
    post.setEntity(builder.build());//  w  w  w .j  a v  a  2  s  .c o  m

    HttpResponse response = client.execute(post);
    int statusCode = response.getStatusLine().getStatusCode();

    HttpEntity resEntity = response.getEntity();

    if (statusCode >= 200 && statusCode <= 299 && resEntity != null) {
        InputStream is = resEntity.getContent();
        try {
            FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target);
        } finally {
            IOUtil.close(is);
        }
    } else if (statusCode >= 500 && statusCode <= 599) {
        InputStream is = resEntity.getContent();
        String message = IOUtil.toString(is, "UTF-8");
        throw new NoHttpResponseException("Server failed with " + message);
    } else {
        throw new MojoExecutionException("Signer replied " + response.getStatusLine());
    }
}

From source file:org.artags.android.app.util.http.HttpUtil.java

/**
 * Post data and attachements/*from  w  w w .j  a v a2 s . c  o m*/
 * @param url The POST url
 * @param params Parameters
 * @param files Files
 * @return The return value
 * @throws HttpException If an error occurs
 */
public static String post(String url, HashMap<String, String> params, HashMap<String, File> files)
        throws HttpException {
    String ret = "";
    try {
        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(url);

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String key : files.keySet()) {
            FileBody bin = new FileBody(files.get(key));
            reqEntity.addPart(key, bin);
        }

        for (String key : params.keySet()) {
            String val = params.get(key);

            reqEntity.addPart(key, new StringBody(val, Charset.forName("UTF-8")));
        }
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);

        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            Log.i("ARTags:HttpUtil:Post:Response", ret);
        }

        //return response;
    } catch (Exception e) {
        Log.e("ARTags:HttpUtil", "Error : " + e.getMessage());
        throw new HttpException(e.getMessage());
    }
    return ret;
}

From source file:ADP_Streamline.CURL2.java

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

    String json = null;//from w  w  w .  j  a  v a 2s  .  co  m
    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:org.opencastproject.remotetest.server.resource.FilesResources.java

public static HttpResponse postFile(TrustedHttpClient client, String mediaPackageID,
        String mediaPackageElementID, String media) throws Exception {
    HttpPost post = new HttpPost(
            getServiceUrl() + "mediapackage/" + mediaPackageElementID + "/" + mediaPackageElementID);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(new File(media)));
    post.setEntity(entity);// w ww. j  av a2 s  .  c o  m
    return client.execute(post);
}

From source file:net.bither.api.UploadAvatarApi.java

@Override
public HttpEntity getHttpEntity() throws Exception {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart(FILE_KEY, new FileBody(this.mFile));
    return multipartEntity;
}

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

/**
 * @param audio Audio file/*from  ww w.  ja  va2s  .  c om*/
 * @throws UnsupportedEncodingException
 */
public void setSourceFile(File audio) throws UnsupportedEncodingException {
    entity.addPart("data", new FileBody(audio));
}

From source file:ADP_Streamline.CURL.java

public void UploadFiles() throws ClientProtocolException, IOException {

    String filePath = "file_path";
    String url = "http://localhost/files";
    File file = new File(filePath);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(file));
    HttpResponse returnResponse = Request.Post(url).body(entity).execute().returnResponse();
    System.out.println("Response status: " + returnResponse.getStatusLine().getStatusCode());
    System.out.println(EntityUtils.toString(returnResponse.getEntity()));
}

From source file:com.afrisoftech.lib.PDF2ExcelConverter.java

public static void convertPDf2Excel(String pdfFile2Convert) throws Exception {
    if (pdfFile2Convert.length() < 3) {
        System.out.println("File to convert is mandatory!");
        javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
    } else {/*from   w w  w .  java2  s . com*/

        final String apiKey = "ktxpfvf0i5se";
        final String format = "xlsx-single".toLowerCase();
        final String pdfFilename = pdfFile2Convert;

        if (!formats.contains(format)) {
            System.out.println("Invalid output format: \"" + format + "\"");
        }

        // Avoid cookie warning with default cookie configuration
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

        File inputFile = new File(pdfFilename);

        if (!inputFile.canRead()) {
            System.out.println("Can't read input PDF file: \"" + pdfFilename + "\"");
            javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
        }

        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .build()) {
            HttpPost httppost = new HttpPost("https://pdftables.com/api?format=" + format + "&key=" + apiKey);
            FileBody fileBody = new FileBody(inputFile);

            HttpEntity requestBody = MultipartEntityBuilder.create().addPart("f", fileBody).build();
            httppost.setEntity(requestBody);

            System.out.println("Sending request");

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    System.out.println(response.getStatusLine());
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Internet connection is a must. Consult IT administrator for further assistance");
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    final String outputFilename = getOutputFilename(pdfFilename,
                            format.replaceFirst("-.*$", ""));
                    System.out.println("Writing output to " + outputFilename);

                    final File outputFile = new File(outputFilename);
                    FileUtils.copyInputStreamToFile(resEntity.getContent(), outputFile);
                    if (java.awt.Desktop.isDesktopSupported()) {
                        try {
                            java.awt.Desktop.getDesktop().open(outputFile);
                        } catch (IOException ex) {
                            javax.swing.JOptionPane.showMessageDialog(new java.awt.Frame(), ex.getMessage());
                            ex.printStackTrace(); //Exceptions.printStackTrace(ex);
                        }
                    }
                } else {
                    System.out.println("Error: file missing from response");
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Error: file missing from response! Internet connection is a must.");
                }
            }
        }
    }
}