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.asplode.tumblr.PhotoPost.java

/**
 * @param image Image file//from ww w.j  a va 2s  .c om
 * @throws UnsupportedEncodingException
 */
public void setSourceFile(File image) throws UnsupportedEncodingException {
    entity.addPart("data", new FileBody(image));
}

From source file:com.msds.km.service.Impl.YunmaiAPIDrivingLicenseRecognitionServcieiImpl.java

@Override
protected DrivingLicense recognitionInternal(File file) throws RecognitionException {
    try {/*from   ww  w .  j av  a 2 s .com*/
        HttpPost httppost = new HttpPost(POST_URL);
        FileBody fileBody = new FileBody(file);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("img", fileBody)
                .addTextBody("action", "driving").addTextBody("callbackurl", "/idcard/").build();

        httppost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            String content = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());
            return this.parseDrivingLicense(content);
        } catch (IOException e) {
            throw new RecognitionException(
                    "can not post request to the url:" + POST_URL + ", please check the network.", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                throw new RecognitionException(
                        "can not post request to the url:" + POST_URL + ", please check the network.", e);
            }
        }
    } catch (FileNotFoundException e) {
        throw new RecognitionException(
                "the file can not founded:" + file.getAbsolutePath() + ", please check the file.", e);
    } catch (ClientProtocolException e) {
        throw new RecognitionException(
                "can not post request to the url:" + POST_URL + ", please check the network.", e);
    } catch (IOException e) {
        throw new RecognitionException(
                "can not post request to the url:" + POST_URL + ", please check the network.", e);
    }
}

From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java

@Override
protected Void doInBackground(Void... voids) {
    try {//from w  ww . j  a va 2 s . c om

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"),
                ContentType.create("Multipart/related", "UTF-8"));
        builder.addPart("image", new FileBody(new File(path)));

        InputStream inputStream = null;
        HttpClient httpClient = AndroidHttpClient.newInstance("Android");

        String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, "");
        String encodeCarNo = "";

        if (false == carNo.equals("")) {
            encodeCarNo = URLEncoder.encode(carNo, "UTF-8");
        }
        HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo);
        httpPost.setEntity(builder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:mesquite.zephyr.GarliRunnerCIPRes.GarliRunnerCIPRes.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);
        final File file2 = new File(externalProcRunner.getInputFilePath(CONFIGFILENUMBER));
        FileBody fb2 = new FileBody(file2);
        builder.addPart("input.upload_conffile_", fb2);
    }/* w w  w. j a va 2 s. c o m*/
}

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;
    }/*ww  w .j a  v a2 s.  c  o 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.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   w ww.  j  a  v a 2 s  .c  o  m
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

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

/**
 * Upload scanned document to OpenKM/* ww  w.  j a  v a 2  s .  co 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:uk.ac.diamond.scisoft.feedback.FeedbackRequest.java

/**
 * Method used to submit a form data/file through HTTP to a GAE servlet
 * /* w  w w.java 2 s. co  m*/
 * @param email
 * @param to
 * @param name
 * @param subject
 * @param messageBody
 * @param attachmentFiles
 * @param monitor
 */
public static IStatus doRequest(String email, String to, String name, String subject, String messageBody,
        List<File> attachmentFiles, IProgressMonitor monitor) throws Exception {
    Status status = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    FeedbackProxy.init();
    host = FeedbackProxy.getHost();
    port = FeedbackProxy.getPort();

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    // if there is a proxy
    if (host != null) {
        HttpHost proxy = new HttpHost(host, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    try {
        HttpPost httpost = new HttpPost(SERVLET_URL + SERVLET_NAME);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("name", new StringBody(name));
        entity.addPart("email", new StringBody(email));
        entity.addPart("to", new StringBody(to));
        entity.addPart("subject", new StringBody(subject));
        entity.addPart("message", new StringBody(messageBody));

        // add attachement files to the multipart entity
        for (int i = 0; i < attachmentFiles.size(); i++) {
            if (attachmentFiles.get(i) != null && attachmentFiles.get(i).exists())
                entity.addPart("attachment" + i + ".html", new FileBody(attachmentFiles.get(i)));
        }

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        httpost.setEntity(entity);

        // HttpPost post = new HttpPost("http://dawnsci-feedback.appspot.com/dawnfeedback?name=baha&email=baha@email.com&subject=thisisasubject&message=thisisthemessage");
        HttpResponse response = httpclient.execute(httpost);

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        final String reasonPhrase = response.getStatusLine().getReasonPhrase();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            logger.debug("Status code 200");
            status = new Status(IStatus.OK, "Feedback successfully sent", "Thank you for your contribution");
        } else {
            logger.debug("Feedback email not sent - HTTP response: " + reasonPhrase);
            status = new Status(IStatus.WARNING, "Feedback not sent",
                    "The response from the server is the following:\n" + reasonPhrase
                            + "\nClick on OK to submit your feedback using the online feedback form available at http://dawnsci-feedback.appspot.com/");
        }
        logger.debug("HTTP Response: " + response.getStatusLine());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return status;
}

From source file:com.onaio.steps.helper.UploadFileTask.java

@Override
protected Boolean doInBackground(File... files) {
    if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL));
        try {/*  ww  w .  j a  v a  2  s .  co m*/
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName("UTF-8"));
            multipartEntity.addPart("file", new FileBody(files[0]));
            httpPost.setEntity(multipartEntity);
            httpClient.execute(httpPost);
            new CustomNotification().notify(activity, R.string.export_complete,
                    R.string.export_complete_message);
            return true;
        } catch (IOException e) {
            new Logger().log(e, "Export failed.");
            new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
        }
    } else {
        new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
    }

    return false;
}