Example usage for org.apache.http.entity.mime MultipartEntity addPart

List of usage examples for org.apache.http.entity.mime MultipartEntity addPart

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

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  w  w  .j  av  a2 s . co 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:org.jutge.joc.porra.service.EmailService.java

/**
 * Mighty delicate a process it is to send an email through the Raco webmail frontend. Let me break it down:
 * You need to log in as you'd normally do in the Raco. After a couple of redirects to the CAS server, you should be inside.
 * Then you issue a GET for the mail compose form. The response contains a form token to be used in the actual multipart POST that should send the mail.
 * The minute they change the login system or the webmail styles, this'll probably break down LOL: Let's hope they keep it this way til the Joc d'EDA is over
 * @param userAccount user to send the mail to
 * @param message the message body/*from   w w w.  j a va  2  s  .  com*/
 * @throws Exception should anything crash
 */
private void sendMail(final Account userAccount, final String message) throws Exception {
    // Enviar mail pel Raco
    // Authenticate
    final List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("service", "https://raco.fib.upc.edu/oauth/gestio-api/api.jsp"));
    params.add(new BasicNameValuePair("loginDirecte", "true"));
    params.add(new BasicNameValuePair("username", "XXXXXXXX"));
    params.add(new BasicNameValuePair("password", "XXXXXXXX"));
    HttpPost post = new HttpPost("https://raco.fib.upc.edu/cas/login");
    post.setEntity(new UrlEncodedFormEntity(params));
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) {
            boolean isRedirect = false;
            try {
                isRedirect = super.isRedirected(request, response, context);
            } catch (ProtocolException e) {
                EmailService.this.logger.error(e.getMessage());
            }
            if (!isRedirect) {
                final int responseCode = response.getStatusLine().getStatusCode();
                isRedirect = responseCode == 301 || responseCode == 302;
            }
            return isRedirect;
        }
    });
    HttpResponse response = httpClient.execute(post);
    HttpEntity entity = response.getEntity();
    EntityUtils.consumeQuietly(entity);
    // get form page
    final HttpGet get = new HttpGet("https://webmail.fib.upc.es/horde/imp/compose.php?thismailbox=INBOX&uniq="
            + System.currentTimeMillis());
    response = httpClient.execute(get);
    entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    // Find form action with uniq parameter 
    Pattern pattern = Pattern.compile(RacoUtils.RACO_MAIL_ACTION_PATTERN);
    Matcher matcher = pattern.matcher(responseBody);
    matcher.find();
    final String action = matcher.group();
    // formtoken
    responseBody = responseBody.substring(matcher.end(), responseBody.length());
    pattern = Pattern.compile(RacoUtils.RACO_FORMTOKEN_PATTERN);
    matcher = pattern.matcher(responseBody);
    matcher.find();
    String formToken = matcher.group();
    formToken = formToken.substring(28, formToken.length());
    // to
    final String email = userAccount.getEmail();
    // Send mail - it's a multipart post
    final MultipartEntity multipart = new MultipartEntity();
    multipart.addPart("MAX_FILE_SIZE", new StringBody("1038090240"));
    multipart.addPart("actionID", new StringBody("send_message"));
    multipart.addPart("__formToken_compose", new StringBody(formToken));
    multipart.addPart("messageCache", new StringBody(""));
    multipart.addPart("spellcheck", new StringBody(""));
    multipart.addPart("page", new StringBody(""));
    multipart.addPart("start", new StringBody(""));
    multipart.addPart("thismailbox", new StringBody("INBOX"));
    multipart.addPart("attachmentAction", new StringBody(""));
    multipart.addPart("reloaded", new StringBody("1"));
    multipart.addPart("oldrtemode", new StringBody(""));
    multipart.addPart("rtemode", new StringBody("1"));
    multipart.addPart("last_identity", new StringBody("0"));
    multipart.addPart("from", new StringBody("porra-joc-eda@est.fib.upc.edu"));
    multipart.addPart("to", new StringBody(email));
    multipart.addPart("cc", new StringBody(""));
    multipart.addPart("bcc", new StringBody(""));
    multipart.addPart("subject", new StringBody("Activacio Porra Joc EDA"));
    multipart.addPart("charset", new StringBody("UTF-8"));
    multipart.addPart("save_sent_mail", new StringBody("on"));
    multipart.addPart("message", new StringBody(message));
    multipart.addPart("upload_1", new StringBody(""));
    multipart.addPart("upload_disposition_1", new StringBody("attachment"));
    multipart.addPart("save_attachments_select", new StringBody("0"));
    multipart.addPart("link_attachments", new StringBody("0"));
    post = new HttpPost("https://webmail.fib.upc.es/horde/imp/" + action);
    post.setEntity(multipart);
    response = httpClient.execute(post);
    EntityUtils.consumeQuietly(entity);
    this.logger.info("EmailService.sendMail done");
}

From source file:com.surevine.alfresco.connector.BaseAlfrescoHttpConnector.java

/**
 * POST multipart form parts to a URL using JSON encoding and parse out a JSON
 * object from the response./*from   www.jav a 2 s.  c om*/
 * 
 * @param url
 *          URL to post to
 * @param content
 *          The String value of the post request
 * @return The JSON response
 * @throws AlfrescoException
 *           On any HTTP error
 */
protected AlfrescoHttpResponse doHttpPost(final String url, final Map<String, ContentBody> parts)
        throws AlfrescoException {
    final HttpPost request = new HttpPost(url);
    final MultipartEntity entity = new MultipartEntity();

    for (final String name : parts.keySet()) {
        entity.addPart(name, parts.get(name));
    }

    request.setEntity(entity);

    return fetch(request);
}

From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java

private void constructMultipartRequest(HttpEntityEnclosingRequestBase httpRequest, String requestBody,
        String mediaType, List<RestAttachment> attachments) throws UnsupportedEncodingException {
    MultipartEntity multipartEntity = new MultipartEntity();
    if (requestBody != null) {
        multipartEntity.addPart("payload", new StringBody(requestBody, mediaType, Charset.forName("UTF-8")));
    }//from w w  w  .  ja  va 2 s .c om
    int attachmentCount = 0;
    for (RestAttachment attachment : attachments) {
        String attachmentName = "attachment" + (++attachmentCount);
        multipartEntity.addPart(attachmentName,
                new ByteArrayBody(attachment.getBinaryContent(), attachment.getMediaType(), attachmentName));
    }

    httpRequest.setEntity(multipartEntity);
}

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);//w w w  .  jav a2  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:ws.munday.youtubecaptionrate.WebRequest.java

public String PostFileWithBasicAuthorization(String uri, String filename, String Username, String Password)
        throws ClientProtocolException, IOException, URISyntaxException {
    _post = new HttpPost(uri);
    _post.addHeader("Authorization", "Basic " + Base64.encodeString(Username + ":" + Password));
    File f = new File(new URI(filename));
    MultipartEntity e = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody fb = new FileBody(f);
    e.addPart("torrent_file", fb);
    StringBody sb = new StringBody("add-file");
    e.addPart("action", sb);
    _post.setEntity(e);//from  w w w  .j  a  v a 2  s .  co  m
    _response = _client.execute(_post);

    return GetResponseText(_response.getEntity().getContent());
}

From source file:com.jigarmjoshi.service.task.UploaderTask.java

private final boolean uploadEntryReport(Report entry) {
    if (entry == null || entry.getUploaded()) {
        return true;
    }/*w w  w . j  av a2s .c o  m*/
    boolean resultFlag = false;
    try {
        Log.i(UploaderTask.class.getSimpleName(), "uploading " + entry.getImageFileName());
        Bitmap bm = BitmapFactory.decodeFile(entry.getImageFileName());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 60, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(this.serverUrl + "/uploadEntryRecord");
        ByteArrayBody bab = new ByteArrayBody(data, "report.jpg");
        // File file= new File("/mnt/sdcard/forest.png");
        // FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("lat", new StringBody(Utility.encode(entry.getLat())));
        reqEntity.addPart("lon", new StringBody(Utility.encode(entry.getLon())));
        reqEntity.addPart("priority", new StringBody(Utility.encode(entry.getPriority())));
        reqEntity.addPart("fileName", new StringBody(Utility.encode(entry.getImageFileName())));
        reqEntity.addPart("reporterId", new StringBody(Utility.encode(entry.getId())));
        reqEntity.addPart("uploaded", bab);
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder responseString = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            responseString = responseString.append(sResponse);
        }
        Log.i(UploaderTask.class.getSimpleName(), responseString.toString());
        if ("SUCCESS".equalsIgnoreCase(responseString.toString())) {
            resultFlag = true;
            if (entry.getImageFileName() != null) {
                File imageFileToDelete = new File(entry.getImageFileName());
                boolean deleted = imageFileToDelete.delete();

                if (deleted) {
                    Log.i(UploaderTask.class.getSimpleName(), "deleted = ?" + deleted);
                    MediaScannerConnection.scanFile(context, new String[] {

                            imageFileToDelete.getAbsolutePath() },

                            null, new MediaScannerConnection.OnScanCompletedListener() {

                                public void onScanCompleted(String path, Uri uri)

                            {

                                }

                            });

                }
            }
        }

    } catch (Exception ex) {
        Log.e(UploaderTask.class.getSimpleName(), "failed to upload", ex);
        resultFlag = false;
    }
    return resultFlag;
}

From source file:net.kidlogger.kidlogger.SendTestReport.java

private void sendPOST() {
    File fs = getFile();//w  ww .  ja v a  2  s.c o  m
    Date now = new Date();
    String fileDate = String.format("%td/%tm/%tY %tT", now, now, now, now);
    String devField = Settings.getDeviceField(context);
    if (devField.equals("undefined") || devField.equals(""))
        return;
    try {
        HttpClient client = new DefaultHttpClient();
        String postUrl = context.getString(R.string.upload_link);
        //String postUrl = "http://10.0.2.2/denwer/";
        HttpPost post = new HttpPost(postUrl);
        FileBody bin = new FileBody(fs, "text/html", fs.getName());
        StringBody sb1 = new StringBody(devField);
        StringBody sb2 = new StringBody("HTML");
        StringBody sb3 = new StringBody("Andriod_2_2");
        StringBody sb4 = new StringBody("1.0");
        StringBody sb5 = new StringBody(fileDate);

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        reqEntity.addPart("file", bin);
        reqEntity.addPart("device", sb1);
        reqEntity.addPart("content", sb2);
        reqEntity.addPart("client-ver", sb3);
        reqEntity.addPart("app-ver", sb4);
        reqEntity.addPart("client-date-time", sb5);

        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            String pStatus = EntityUtils.toString(resEntity);
            if (pStatus.equalsIgnoreCase("Ok")) {
                fs.delete();
                testRes.setText("Response: " + pStatus);
            } else {
                //Log.i("sendPOST", pStatus);
            }
            testRes.setText("Response: " + pStatus);
            //Log.i("sendPOST", "Response: " + pStatus);
        }
    } catch (Exception e) {
        //Log.i("sendPOST", e.toString());
    }
}

From source file:org.semantictools.jsonld.impl.AppspotContextPublisher.java

@Override
public void publish(LdAsset asset) throws LdPublishException {

    String uri = asset.getURI();// w w w. ja v  a 2 s  .co  m

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(SERVLET_URL);
    post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx",
            Charset.forName("UTF-8"));

    try {

        String content = asset.loadContent();

        entity.addPart(URI, new StringBody(uri));
        entity.addPart(FILE_UPLOAD, new StringBody(content));
        post.setEntity(entity);

        logger.debug("uploading... " + uri);

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

        client.getConnectionManager().shutdown();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new LdPublishException(uri, null);
        }

    } catch (Exception e) {
        throw new LdPublishException(uri, e);
    }

}

From source file:com.qcloud.CloudClient.java

public String postfiles(String url, Map<String, String> header, Map<String, Object> body, byte[][] data,
        String[] pornFile) throws UnsupportedEncodingException, IOException {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("accept", "*/*");
    httpPost.setHeader("user-agent", "qcloud-java-sdk");
    if (header != null) {
        for (String key : header.keySet()) {
            httpPost.setHeader(key, header.get(key));
        }//  www.  j  a  va2  s.  c o  m
    }

    if (false == header.containsKey("Content-Type")
            || header.get("Content-Type").equals("multipart/form-data")) {
        MultipartEntity multipartEntity = new MultipartEntity();
        if (body != null) {
            for (String key : body.keySet()) {
                multipartEntity.addPart(key, new StringBody(body.get(key).toString()));
            }
        }

        if (data != null) {
            for (int i = 0; i < data.length; i++) {
                ContentBody contentBody = new ByteArrayBody(data[i], pornFile[i]);
                multipartEntity.addPart("image[" + Integer.toString(i) + "]", contentBody);
            }
        }
        httpPost.setEntity(multipartEntity);
    }

    //        HttpHost proxy = new HttpHost("127.0.0.1",8888);
    //        mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

    HttpResponse httpResponse = mClient.execute(httpPost);
    int code = httpResponse.getStatusLine().getStatusCode();
    return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}