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

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

Introduction

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

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:com.alta189.deskbin.services.image.ImgurService.java

@Override
public String upload(File image) throws ImageServiceException {
    try {/*w  ww  . j a  va 2  s  .  co  m*/
        HttpPost post = new HttpPost(UPLOAD_URL);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("key", new StringBody(apikey, Charset.forName("UTF-8")));
        entity.addPart("type", new StringBody("file", Charset.forName("UTF-8")));
        FileBody fileBody = new FileBody(image);
        entity.addPart("image", fileBody);
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ImageServiceException(
                    "Error accessing imgur. Status code: " + response.getStatusLine().getStatusCode());
        }
        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = new JSONObject(json).getJSONObject("upload").getJSONObject("links");
        return jsonObject.getString("imgur_page");
    } catch (Exception e) {
        throw new ImageServiceException(e);
    }
}

From source file:jp.ac.tokushima_u.is.ll.io.LanguageJsonHandler.java

public ArrayList<ContentProviderOperation> parse(ContentResolver resolver) {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    Uri uri = Languages.CONTENT_URI;
    String sortOrder = SyncColumns.UPDATED + " desc";
    Cursor cursor = resolver.query(uri, LanguagesQuery.PROJECTION, null, null, sortOrder);
    try {/*from   ww w . j a va 2s.  c o m*/
        if (cursor.moveToFirst()) {
            Log.d(TAG, "Language has been inserted");
            int count = cursor.getCount();
            if (count > 3) {
                return batch;
            }
        }
    } finally {
        cursor.close();
    }

    HttpPost httpPost = new HttpPost(this.systemUrl + this.syncServiceUrl + this.languageSearchUrl);
    try {
        DefaultHttpClient client = HttpClientFactory.createHttpClient();
        MultipartEntity params = new MultipartEntity();
        httpPost.setEntity(params);
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = convertStreamToString(instream);
            instream.close();
            JSONObject json = new JSONObject(result);
            if (json != null) {
                JSONArray array = json.getJSONArray("languages");
                if (array != null) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject o = array.getJSONObject(i);
                        String languageId = o.getString("id");
                        if (languageId == null || languageId.length() <= 0)
                            continue;

                        ContentProviderOperation.Builder builder = ContentProviderOperation
                                .newInsert(Languages.CONTENT_URI);

                        builder.withValue(Languages.LANGUAGE_ID, languageId);
                        if (o.getString("code") != null && o.getString("code").length() > 0
                                && !"null".equals(o.getString("code")))
                            builder.withValue(Languages.CODE, o.getString("code"));
                        if (o.getString("name") != null && o.getString("name").length() > 0
                                && !"null".equals(o.getString("name")))
                            builder.withValue(Languages.NAME, o.getString("name"));
                        builder.withValue(SyncColumns.UPDATED, Calendar.getInstance().getTimeInMillis());
                        batch.add(builder.build());
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.d(TAG, "exception occured", e);
    }

    return batch;
}

From source file:org.thomwiggers.Jjoyce.comet.CometJoyceClientRelay.java

public void sendStream(String token, Stream stream, boolean blocking) {
    if (!this.token.equals(token))
        throw new IllegalArgumentException("Wrong token!");

    this.conditionMessageIn = lock.newCondition();
    this.conditionOut = lock.newCondition();

    MultipartEntity multipartStream = new MultipartEntity();
    multipartStream.addPart("stream", stream);

    final HttpPost post = new HttpPost(
            String.format("http://%s:%s%s?m=%s", hub.getHost(), hub.getPort(), hub.getPath()));

    post.setEntity(multipartStream);/*from  w  ww .ja  v a 2s  . c  o  m*/

    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                httpClient.execute(post);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    t.start();

    if (blocking) {
        try {
            t.join();
        } catch (InterruptedException e) {

        }
    }

}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java

/**
 * This method sends HTTP request to add order.
 *
 * @param user/*from w  ww .j a  va2s.co  m*/
 * @param handler
 * @param orderInfo
 * @return
 */
public static String sendAddOrderRequest(User user, Handler handler, TableReservationInfo orderInfo) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
    HttpConnectionParams.setSoTimeout(httpParameters, 15000);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(ADD_ORDER_URL);
    Log.e(TAG, "ADD_ORDER_URL = " + ADD_ORDER_URL);

    MultipartEntity multipartEntity = new MultipartEntity();

    // user details
    String userType = null;
    String orderUUID = null;
    try {

        if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
            userType = "facebook";
            multipartEntity.addPart("order_customer_name", new StringBody(
                    user.getUserFirstName() + " " + user.getUserLastName(), Charset.forName("UTF-8")));
        } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
            userType = "twitter";
            multipartEntity.addPart("order_customer_name",
                    new StringBody(user.getUserName(), Charset.forName("UTF-8")));
        } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) {
            userType = "ibuildapp";
            multipartEntity.addPart("order_customer_name",
                    new StringBody(user.getUserName(), Charset.forName("UTF-8")));

        } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) {
            userType = "guest";
            multipartEntity.addPart("order_customer_name", new StringBody("Guest", Charset.forName("UTF-8")));
        }

        multipartEntity.addPart("user_type", new StringBody(userType, Charset.forName("UTF-8")));
        multipartEntity.addPart("user_id", new StringBody(user.getAccountId(), Charset.forName("UTF-8")));
        multipartEntity.addPart("app_id", new StringBody(orderInfo.getAppid(), Charset.forName("UTF-8")));
        multipartEntity.addPart("module_id", new StringBody(orderInfo.getModuleid(), Charset.forName("UTF-8")));

        // order UUID
        orderUUID = UUID.randomUUID().toString();
        multipartEntity.addPart("order_uid", new StringBody(orderUUID, Charset.forName("UTF-8")));

        // order details
        Date tempDate = orderInfo.getOrderDate();
        tempDate.setHours(orderInfo.getOrderTime().houres);
        tempDate.setMinutes(orderInfo.getOrderTime().minutes);
        tempDate.getTimezoneOffset();
        String timeZone = timeZoneToString();

        multipartEntity.addPart("time_zone", new StringBody(timeZone, Charset.forName("UTF-8")));
        multipartEntity.addPart("order_date_time",
                new StringBody(Long.toString(tempDate.getTime() / 1000), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_persons",
                new StringBody(Integer.toString(orderInfo.getPersonsAmount()), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_spec_request",
                new StringBody(orderInfo.getSpecialRequest(), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_customer_phone",
                new StringBody(orderInfo.getPhoneNumber(), Charset.forName("UTF-8")));
        multipartEntity.addPart("order_customer_email",
                new StringBody(orderInfo.getCustomerEmail(), Charset.forName("UTF-8")));

        // add security part
        multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8")));
        multipartEntity.addPart("token", new StringBody(Statics.appToken, Charset.forName("UTF-8")));

    } catch (Exception e) {
        Log.d("", "");
    }

    httppost.setEntity(multipartEntity);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        String strResponseSaveGoal = httpclient.execute(httppost, responseHandler);
        Log.d("sendAddOrderRequest", "");
        String res = JSONParser.parseQueryError(strResponseSaveGoal);

        if (res == null || res.length() == 0) {
            return orderUUID;
        } else {
            handler.sendEmptyMessage(ADD_REQUEST_ERROR);
            return null;
        }
    } catch (ConnectTimeoutException conEx) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    } catch (ClientProtocolException ex) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    } catch (IOException ex) {
        handler.sendEmptyMessage(ADD_REQUEST_ERROR);
        return null;
    }
}

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));
        }//  ww  w  .  ja v  a2  s  .  c  om
    }

    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");
}

From source file:org.sonar.plugins.web.markup.validation.MarkupValidator.java

/**
 * Post contents of HTML file to the W3C validation service. In return, receive a Soap response message.
 *
 * @see http://validator.w3.org/docs/api.html
 *//*from w ww.  j  a v  a2  s. co m*/
private void postHtmlContents(InputFile inputfile) {

    HttpPost post = new HttpPost(validationUrl);
    HttpResponse response = null;

    post.addHeader("User-Agent", "sonar-w3c-markup-validation-plugin/1.0");

    try {

        LOG.info("W3C Validate: " + inputfile.getRelativePath());

        // file upload
        MultipartEntity multiPartRequestEntity = new MultipartEntity();
        String charset = CharsetDetector.detect(inputfile.getFile());
        FileBody fileBody = new FileBody(inputfile.getFile(), TEXT_HTML_CONTENT_TYPE, charset);
        multiPartRequestEntity.addPart(UPLOADED_FILE, fileBody);

        // set output format
        multiPartRequestEntity.addPart(OUTPUT, new StringBody(SOAP12));

        post.setEntity(multiPartRequestEntity);
        response = executePostMethod(post);

        // write response to report file
        if (response != null) {
            writeResponse(response, inputfile);
        }

    } catch (UnsupportedEncodingException e) {
        LOG.error(e);
    } finally {
        // release any connection resources used by the method
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException ioe) {
                LOG.debug(ioe);
            }
        }
    }
}

From source file:org.opencastproject.remotetest.server.IngestRestEndpointTest.java

@Test
public void testUploadClient() throws Exception {
    InputStream is = getClass().getResourceAsStream("/mp-test.zip");
    InputStreamBody fileContent = new InputStreamBody(is, "mp-test.zip");

    // create emptiy MediaPackage
    HttpPost postStart = new HttpPost(BASE_URL + "/ingest/addZippedMediaPackage");

    MultipartEntity mpEntity = new MultipartEntity();
    mpEntity.addPart("workflowDefinitionId", new StringBody("full"));
    mpEntity.addPart("userfile", fileContent);
    postStart.setEntity(mpEntity);/*from  w  w w . j  a  va 2s . c om*/

    HttpResponse response = client.execute(postStart);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

/** Install a bundle using the Felix webconsole HTTP interface, with a specific start level */
public void installBundle(File f, boolean startBundle, int startLevel) throws Exception {

    // Setup request for Felix Webconsole bundle install
    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("install"));
    if (startBundle) {
        entity.addPart("bundlestart", new StringBody("true"));
    }/*from  ww w.  j a  v  a 2s  .  c  o m*/
    entity.addPart("bundlefile", new FileBody(f));

    if (startLevel > 0) {
        entity.addPart("bundlestartlevel", new StringBody(String.valueOf(startLevel)));
        log.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        log.info("Installing bundle {} at default start level", f.getName());
    }

    // Console returns a 302 on success (and in a POST this
    // is not handled automatically as per HTTP spec)
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH).withCredentials(username, password)
            .withEntity(entity)).assertStatus(302);
}

From source file:se.vgregion.util.HTTPUtils.java

public static HttpResponse makePostAttachments(String url, String token, DefaultHttpClient httpclient,
        Attachment attachment) throws Exception {

    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("X-TrackerToken", token);
    httppost.removeHeaders("Connection");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody content = new SizedInputStreamBody(attachment.getData(), attachment.getFilename(),
            attachment.getFileLength());
    mpEntity.addPart("Filedata", content);
    httppost.setEntity(mpEntity);//from  www.  j  a  va  2  s.  c o  m

    return httpclient.execute(httppost);
}

From source file:de.uzk.hki.da.webservice.HttpFileTransmissionClient.java

/**
 * Post file./*from   www. ja va2 s .co m*/
 *
 * @param file the file
 * @param toFile the to file
 */
@SuppressWarnings("finally")
public File postFileAndReadResponse(File file, File toFile) {
    HttpClient httpclient = null;
    ;
    try {
        if (!file.exists()) {
            throw new RuntimeException("Source File does not exist " + file.getAbsolutePath());
        }
        if (url.isEmpty()) {
            throw new RuntimeException("Webservice called but Url is empty");
        }

        httpclient = new DefaultHttpClient();
        logger.info("starting new http client for url " + url);
        HttpPost httppost = new HttpPost(url);
        HttpParams httpRequestParameters = httppost.getParams();
        httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httppost.setParams(httpRequestParameters);

        MultipartEntity multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("fileDescription", new StringBody("doxc Converison"));
        multiPartEntity.addPart("fileName", new StringBody(file.getName()));
        if (sourceMimeType.isEmpty())
            sourceMimeType = "application/octet-stream";
        if (destMimeType.isEmpty())
            destMimeType = "application/octet-stream";
        FileBody fileBody = new FileBody(file, sourceMimeType);
        multiPartEntity.addPart("attachment", fileBody);

        httppost.setEntity(multiPartEntity);

        logger.debug("calling webservice now. recieving response");
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200 && resEntity.getContentType().getValue().startsWith(destMimeType)) {
            InputStream in = resEntity.getContent();

            FileOutputStream fos = new FileOutputStream(toFile);

            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            logger.debug("successfully stored recieved content to " + toFile.getAbsolutePath());
            in.close();
            fos.close();
            cleanup();
        } else {
            logger.error(
                    "Recieved reponse of " + resEntity.getContentType() + ", but expected " + destMimeType);
            printResponse(resEntity);
        }
    } catch (Exception e) {
        logger.error("Exception occured in remotefileTransmission " + e.getStackTrace());
        throw new RuntimeException("Webservice error " + url, e);
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
        return toFile;
    }
}