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, final String mimeType) 

Source Link

Usage

From source file:org.energyos.espi.datacustodian.console.ImportUsagePoint.java

public static void upload(String filename, String url, HttpClient client) throws IOException {
    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filename);
    entity.addPart("file", new FileBody(((File) file), "application/rss+xml"));

    post.setEntity(entity);// w w w.j  a  va  2 s . c  o  m

    client.execute(post);
}

From source file:org.factpub.ui.gui.network.PostFile.java

public static List<String> uploadToFactpub(File file) throws Exception {
    List<String> status = new ArrayList<String>();
    int i = 0;/*  www .  j a  v  a  2 s  .c  om*/

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    String postUrl = FEConstants.SERVER_POST_HANDLER + "?id=" + AuthMediaWikiIdHTTP.authorisedUser + "&ps="
            + AuthMediaWikiIdHTTP.userPassword;

    HttpPost httppost = new HttpPost(postUrl);

    System.out.println(postUrl);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "json");

    // name must be "uploadfile". this is same on the server side.
    mpEntity.addPart(FEConstants.SERVER_UPLOAD_FILE_NAME, cbFile);

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

    System.out.println(response.getStatusLine());

    if (response.getStatusLine().toString().contains("502 Bad Gateway")) {
        status.add("Looks server is down.");
    } else {
        if (resEntity != null) {
            status.add(EntityUtils.toString(resEntity));
            System.out.println(status.get(i));
            i++;
        }

        if (resEntity != null) {
            resEntity.consumeContent();
        }
    }
    httpclient.getConnectionManager().shutdown();

    //String status = "Upload Success!";
    return status;
}

From source file:mobi.salesforce.client.upload.DemoFileUploader.java

public void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription)
        throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(urlString);
    try {//from   ww  w  .  ja  v a2 s. c  om
        // Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("fileDescription",
                new StringBody(fileDescription != null ? fileDescription : ""));
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));

        FileBody fileBody = new FileBody(file, "application/octect-stream");
        // Prepare payload
        multiPartEntity.addPart("attachment", fileBody);

        // Set to request body
        postRequest.setEntity(multiPartEntity);

        // Send request
        HttpResponse response = client.execute(postRequest);

        // Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());
        }
    } catch (Exception ex) {
    }
}

From source file:com.lambdasoup.panda.PandaHttp.java

static String postFile(String url, Map<String, String> params, Properties properties, File file) {
    Map<String, String> sParams = signedParams("POST", url, params, properties);
    String flattenParams = canonicalQueryString(sParams);
    String requestUrl = "http://" + properties.getProperty("api-host") + ":80/v2" + url + "?" + flattenParams;

    HttpPost httpPost = new HttpPost(requestUrl);
    String stringResponse = null;
    FileBody bin = new FileBody(file, "application/octet-stream");
    try {/*  ww  w . j a v  a  2s  .  c  o  m*/
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", bin);

        httpPost.setEntity(entity);

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpResponse response = httpclient.execute(httpPost);
        stringResponse = EntityUtils.toString(response.getEntity());

    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringResponse;
}

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 w  w w.  j a va  2  s  .c  o  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:ca.mcgill.hs.uploader.UploadThread.java

/**
 * Executes the upload in a separate thread
 *//*from w  w  w.jav a 2  s.c om*/

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    int finalStatus = Constants.STATUS_UNKNOWN_ERROR;
    boolean countRetry = false;
    int retryAfter = 0;
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    String filename = null;

    http_request_loop: while (true) {
        try {
            final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
            wakeLock.acquire();

            filename = mInfo.mFileName;
            final File file = new File(filename);
            if (!file.exists()) {
                Log.e(Constants.TAG, "file" + filename + " is to be uploaded, but cannot be found.");
                finalStatus = Constants.STATUS_FILE_ERROR;
                break http_request_loop;
            }
            client = AndroidHttpClient.newInstance(Constants.DEFAULT_USER_AGENT, mContext);
            Log.v(Constants.TAG, "initiating upload for " + mInfo.mUri);
            final HttpPost request = new HttpPost(Constants.UPLOAD_URL);
            request.addHeader("MAC", NetworkHelper.getMacAddress(mContext));

            final MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("uploadedfile", new FileBody(file, "binary/octet-stream"));
            request.setEntity(mpEntity);

            HttpResponse response;
            try {
                response = client.execute(request);
                final HttpEntity resEntity = response.getEntity();

                String responseMsg = null;
                if (resEntity != null) {
                    responseMsg = EntityUtils.toString(resEntity);
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
                if (resEntity != null) {
                    resEntity.consumeContent();
                }

                if (!responseMsg.contains("SUCCESS 0x64asv65")) {
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
            } catch (final IllegalArgumentException e) {
                finalStatus = Constants.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (final IOException e) {
                if (!NetworkHelper.isNetworkAvailable(mContext)) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    Log.d(Constants.TAG, "IOException trying to excute request for " + mInfo.mUri + " : " + e);
                    finalStatus = Constants.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                Log.v(Constants.TAG, "got HTTP response code 503");
                finalStatus = Constants.STATUS_RUNNING_PAUSED;
                countRetry = true;

                retryAfter = Constants.MIN_RETRY_AFTER;
                retryAfter += NetworkHelper.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                retryAfter *= 1000;
                request.abort();
                break http_request_loop;
            } else {
                finalStatus = Constants.STATUS_SUCCESS;
            }
            break;
        } catch (final RuntimeException e) {
            finalStatus = Constants.STATUS_UNKNOWN_ERROR;
        } finally {
            mInfo.mHasActiveThread = false;
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
            if (client != null) {
                client.close();
                client = null;
            }
            if (finalStatus == Constants.STATUS_SUCCESS) {
                // TODO: Move the file.
            }
        }
    }

}

From source file:com.mobileuni.helpers.FileManager.java

public void UploadToUrl(String siteUrl, String token, String filepath) {

    String url = siteUrl + "/webservice/upload.php?token=" + token;
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url);
    File file = new File(filepath);

    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            MimeTypeMap.getFileExtensionFromUrl(filepath.substring(filepath.lastIndexOf("."))));

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, mimetype);
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);/*from  www .  ja v a  2s  .  co  m*/
    Log.d(TAG, "upload executing request " + httppost.getRequestLine());
    try {

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        Log.d(TAG, "upload line status " + response.getStatusLine());
        if (resEntity != null) {
            Log.d(TAG, "upload " + EntityUtils.toString(resEntity));
            //JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
        } else {
            Log.d(TAG, "upload error: " + EntityUtils.toString(resEntity));
        }

    } catch (Exception ex) {
        Log.d(TAG, "Error: " + ex);
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:webcamcapture.WebCamCapture.java

void request(String url, String file_name) throws IOException {
    try {//w  ww .  java  2s .  com
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(url);

        String file_path = "C:/Users/darshit/Documents/NetBeansProjects/WebCamCapture/" + file_name;
        File fileToUse = new File(file_path);
        FileBody data = new FileBody(fileToUse, "image/jpeg");

        System.out.println(Inet4Address.getLocalHost().getHostAddress());
        /*MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(fileToUse, "image/jpeg");
        mpEntity.addPart("userfile", cbFile);*/

        // httppost.setEntity(mpEntity);
        //String file_type = "JPG" ;

        MultipartEntity reqEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(fileToUse, "image/jpeg");
        reqEntity.addPart("file", data);

        //reqEntity.addPart("file", cbFile);

        httppost.setEntity(reqEntity);
        //httppost.setEntity(mpEntity); 
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStreamReader is;

        StringBuffer sb = new StringBuffer();
        System.out.println("finalResult " + sb.toString());
        //String line=null;
        /*while((reader.readLine())!=null){
        sb.append(line + "\n");
        }*/

        //StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = sb.toString();
        System.out.println("finalResult " + sb.toString());
        // System.out.println( response ); 
        // String responseString = new BasicResponseHandler().handleResponse(response);
        //System.out.println();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(httpRequestSend.class.getName()).log(Level.SEVERE, null, ex);
        System.out.printf("dsf\n");
    }
}

From source file:me.ziccard.secureit.async.upload.ImagesUploaderTask.java

@Override
protected Void doInBackground(Void... params) {
    HttpClient client = new DefaultHttpClient();

    Log.i("ImagesUploaderTask", "Started");

    int imagesToUpload = 0;

    /*//w  ww. j a v  a2s .  c  o  m
     * If we are using mobile connectivity we upload half of the images
     * stored 
     */
    if (connectivityType == WIFI_CONNECTIVITY) {
        imagesToUpload = prefs.getMaxImages();
    }
    if (connectivityType == MOBILE_CONNECTIVITY) {
        imagesToUpload = prefs.getMaxImages() / 2;
    }
    if (connectivityType == NO_CONNECTIVITY) {
        imagesToUpload = 0;
    }

    for (int imageCount = 0; imageCount < imagesToUpload; imageCount++) {

        String path = Environment.getExternalStorageDirectory().getPath() + prefs.getImagePath() + imageCount
                + ".jpg";

        HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_IMAGES);

        Log.i("ImagesUploaderTask", "Uploading image " + path);

        /*
         * Get image from filesystem
         */
        File image = new File(path);

        //Only if the image exists we upload it 
        if (image.exists()) {

            Log.i("ImagesUploaderTask", "Image exists");

            /*
             * Getting the image from the file system
             */
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("image", new FileBody(image, "image/jpeg"));
            request.setEntity(reqEntity);

            /*
             * Setting the access token
             */
            request.setHeader("access_token", accessToken);

            try {
                HttpResponse response = client.execute(request);

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (String line = null; (line = reader.readLine()) != null;) {
                    builder.append(line).append("\n");
                }

                Log.i("ImagesRecorderTask", "Response:\n" + builder.toString());

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new HttpException();
                }
            } catch (Exception e) {
                Log.e("ImageUploaderTask", "Error uploading image: " + path);
            }
            //otherwise no other image exists
        } else {
            return null;
        }
    }
    return null;
}

From source file:com.openmeap.http.FileHandlingHttpRequestExecuterImpl.java

@Override
public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams)
        throws HttpRequestException {

    // test to determine whether this is a file upload or not.
    Boolean isFileUpload = false;
    for (Object o : postParams.values()) {
        if (o instanceof File) {
            isFileUpload = true;/*from  w  ww  .j a v  a2  s. c o m*/
            break;
        }
    }

    if (isFileUpload) {
        try {
            HttpPost httpPost = new HttpPost(createUrl(url, getParams));

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

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Object o : postParams.entrySet()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o;

                if (entry.getValue() instanceof File) {

                    // For File parameters
                    File file = (File) entry.getValue();
                    FileNameMap fileNameMap = URLConnection.getFileNameMap();
                    String type = fileNameMap.getContentTypeFor(file.toURL().toString());

                    entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type));
                } else {

                    // For usual String parameters
                    entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain",
                            Charset.forName(FormConstants.CHAR_ENC_DEFAULT)));
                }
            }

            httpPost.setEntity(entity);

            return execute(httpPost);
        } catch (Exception e) {
            throw new HttpRequestException(e);
        }
    } else {

        return super.postData(url, getParams, postParams);
    }
}