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:com.easycode.common.HttpUtil.java

public static byte[] httpPost(String url, List<FormItem> blist) throws Exception {
    byte[] ret = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"));
    if (blist != null) {
        for (FormItem f : blist) {
            reqEntity.addPart(f.getName(), f.getCtx());
        }//  w ww  .ja  v  a  2s  .c o m
    }
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        InputStream tis = resEntity.getContent();

        java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = tis.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        ret = out.toByteArray();
    }
    EntityUtils.consume(resEntity);
    try {
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ignore) {
    }
    return ret;
}

From source file:eu.prestoprime.p4gui.connection.WorkflowConnection.java

public static String executeWorkflow(P4Service service, P4Workflow workflow, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws WorkflowRequestException {

    if (dParamsString == null)
        dParamsString = new HashMap<>();
    if (dParamsFile == null)
        dParamsFile = new HashMap<>();

    dParamsString.put("wfID", workflow.toString());

    try {//  ww  w  .j  a  va 2s .  c o  m
        MultipartEntity part = new MultipartEntity();

        for (String key : dParamsString.keySet()) {
            String value = dParamsString.get(key);
            part.addPart(key, new StringBody(value));
        }

        for (String key : dParamsFile.keySet()) {
            File value = dParamsFile.get(key);
            part.addPart(key, new FileBody(value));
        }

        String path = service.getURL() + "/wf/execute/" + workflow;

        logger.debug("Calling " + path);

        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpPost(path);
        request.setHeader("content-data", "multipart/form-data");
        ((HttpPost) request).setEntity(part);
        HttpResponse response = client.executeRequest(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line;
                if ((line = reader.readLine()) != null) {
                    logger.debug("Requested new job: " + line);
                    return line;
                }
            }
        } else {
            logger.debug(response.getStatusLine().toString());
            throw new WorkflowRequestException("Unable to request execution of workflow " + workflow + "...");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new WorkflowRequestException(
            "Something wrong in WorkflowConnection requesting a workflow: no wfID returned...");
}

From source file:ca.sqlpower.enterprise.ClientSideSessionUtils.java

public static ProjectLocation uploadProject(SPServerInfo serviceInfo, String name, File project,
        UserPrompterFactory session, CookieStore cookieStore)
        throws URISyntaxException, ClientProtocolException, IOException, JSONException {
    HttpClient httpClient = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore);
    try {/*w w w .j a  v a2s . com*/
        MultipartEntity entity = new MultipartEntity();
        ContentBody fileBody = new FileBody(project);
        ContentBody nameBody = new StringBody(name);
        entity.addPart("file", fileBody);
        entity.addPart("name", nameBody);

        HttpPost request = new HttpPost(ClientSideSessionUtils.getServerURI(serviceInfo,
                "/" + ClientSideSessionUtils.REST_TAG + "/jcr", "name=" + name));
        request.setEntity(entity);
        JSONMessage message = httpClient.execute(request, new JSONResponseHandler());
        JSONObject response = new JSONObject(message.getBody());
        return new ProjectLocation(response.getString("uuid"), response.getString("name"), serviceInfo);
    } catch (AccessDeniedException e) {
        session.createUserPrompter("You do not have sufficient privileges to create a new workspace.",
                UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;//from   w  ww.  j  ava 2  s  .com
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:no.digipost.android.api.ApiAccess.java

public static void uploadFile(Context context, String uri, File file) throws DigipostClientException {
    try {/*from  w  w w .  ja v a 2  s.c om*/
        try {

            FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM);
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName(ApiConstants.ENCODING));
            multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()),
                    ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING)));
            multipartEntity.addPart("file", filebody);
            multipartEntity.addPart("token", new StringBody(TokenStore.getAccess()));

            URL url = new URL(uri);
            HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection();
            httpsClient.setRequestMethod("POST");
            httpsClient.setDoOutput(true);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength());
            } else {
                httpsClient.setChunkedStreamingMode(0);
            }
            httpsClient.setRequestProperty("Connection", "Keep-Alive");
            httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + "");
            httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION,
                    ApiConstants.BEARER + TokenStore.getAccess());
            httpsClient.addRequestProperty(multipartEntity.getContentType().getName(),
                    multipartEntity.getContentType().getValue());

            try {
                OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream());
                multipartEntity.writeTo(outputStream);
                outputStream.flush();
                NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode());
            } finally {
                httpsClient.disconnect();
            }

        } catch (DigipostInvalidTokenException e) {
            OAuth.updateAccessTokenWithRefreshToken(context);
            uploadFile(context, uri, file);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, context.getString(R.string.error_your_network));
        throw new DigipostClientException(context.getString(R.string.error_your_network));
    }
}

From source file:org.openml.knime.OpenMLWebservice.java

/**
 * Upload an implementation./* w w  w  .j a  v a  2  s  . c  o  m*/
 * 
 * 
 * @param description Implementation description file
 * @param workflow Workflow file
 * @param user Name of the user
 * @param password Password of the user
 * @return Response from the server
 * @throws Exception If communication failed
 */
public static String sendImplementation(final File description, final File workflow, final String user,
        final String password) throws Exception {
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80);
        httpclient.getCredentialsProvider().setCredentials(scope, credentials);
        String url = WEBSERVICEURL + "?f=openml.implementation.upload";
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
        FileBody descBin = new FileBody(description);
        reqEntity.addPart("description", descBin);
        FileBody workflowBin = new FileBody(workflow);
        reqEntity.addPart("source", workflowBin);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() < 200) {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        if (resEntity != null) {
            result = convertStreamToString(resEntity.getContent());
        }
        ErrorDocument errorDoc = null;
        try {
            errorDoc = ErrorDocument.Factory.parse(result);
        } catch (Exception e) {
            // no error XML should mean no error
        }
        if (errorDoc != null && errorDoc.validate()) {
            ErrorDocument.Error error = errorDoc.getError();
            String errorMessage = error.getCode() + " : " + error.getMessage();
            if (error.isSetAdditionalInformation()) {
                errorMessage += " : " + error.getAdditionalInformation();
            }
            throw new Exception(errorMessage);
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
            // ignore
        }
    }
    return result;
}

From source file:com.omt.syncpad.DemoKitActivity.java

private static void postFile() {
    try {/* w  w w . jav a  2  s. c o m*/
        File f = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + fileName);
        mf.writeToFile(f);
        Log.i(TAG, "Midi file generated. Posting file");
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("filename", new StringBody(fileName));
        entity.addPart("fileext", new StringBody(extName));
        entity.addPart("upfile", new FileBody(f));
        HttpClient httpclient = new DefaultHttpClient();
        httppost.setEntity(entity);
        httpclient.execute(httppost);
        //HttpResponse response = httpclient.execute(httppost);
        //Do something with response...
        Log.i(TAG, "File posted");

    } catch (Exception e) {
        // show error
        e.printStackTrace();
        return;
    }
}

From source file:io.github.data4all.util.upload.GpxTrackUtil.java

/**
 * Returns a {@link CloseableUpload} containing all nessesary informations
 * for the upload to the OSM API.//from   www. j a  v a 2  s  .c  o  m
 * 
 * @param context
 *            the application context
 * @param user
 *            The {@link User} who uploads the Changeset.
 * @param track
 *            the gpx xml string
 * @param description
 *            The trace description.
 * @param tags
 *            A string containing tags for the trace. (comma seperated)
 * @param visibility
 *            One of the following: private, public, trackable,
 *            identifiable.
 * @param callback
 *            The callback object for interaction with the
 *            {@link ResultReceiver}.
 * @return {@link CloseableUpload} object
 * @throws OsmException
 *             Indicates an failure in an osm progess.
 */
public static CloseableUpload upload(Context context, User user, String track, String description, String tags,
        String visibility, Callback<Integer> callback) throws OsmException {
    final HttpPost request = getUploadPost(user);

    final MultipartEntity reqEntity = new MultiCallbackEntry(callback);
    final FileBody fileBody = new FileBody(createGpxFile(context, track, "file.gpx"));

    try {
        reqEntity.addPart("file", fileBody);
        reqEntity.addPart("description", new StringBody(description));
        reqEntity.addPart("tags", new StringBody(tags));
        reqEntity.addPart("visibility", new StringBody(visibility));
    } catch (UnsupportedEncodingException e) {
        Log.e(GpxTrackUtil.class.getSimpleName(), "Exception: ", e);
    }

    request.setEntity(reqEntity);
    request.addHeader("ContentType", "multipart/form-data");
    // Setting the Entity

    // final HttpEntity entity = new MultiCallbackEntry(callback);
    // request.setEntity(entity);

    return new CloseableUpload(request);
}

From source file:org.openml.knime.OpenMLWebservice.java

/**
 * Upload a run.//from  www  .ja v a  2  s .c  o  m
 * 
 * @param description Description to the run
 * @param files Run files
 * @param user Name of the user
 * @param password Password of the user
 * @return Response from the server
 * @throws Exception
 */
public static String sendRuns(final File description, final File[] files, final String user,
        final String password) throws Exception {
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials credentials = new UsernamePasswordCredentials(user, password);
    AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80);
    httpclient.getCredentialsProvider().setCredentials(scope, credentials);
    try {
        String url = WEBSERVICEURL + "?f=openml.run.upload";
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
        FileBody descriptionBin = new FileBody(description);
        reqEntity.addPart("description", descriptionBin);
        for (int i = 0; i < files.length; i++) {
            FileBody bin = new FileBody(files[i]);
            reqEntity.addPart("predictions", bin);
        }
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() < 200) {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        if (resEntity != null) {
            result = convertStreamToString(resEntity.getContent());
        }
        ErrorDocument errorDoc = null;
        try {
            errorDoc = ErrorDocument.Factory.parse(result);
        } catch (Exception e) {
            // no error XML should mean no error
        }
        if (errorDoc != null && errorDoc.validate()) {
            ErrorDocument.Error error = errorDoc.getError();
            String errorMessage = error.getCode() + " : " + error.getMessage();
            if (error.isSetAdditionalInformation()) {
                errorMessage += " : " + error.getAdditionalInformation();
            }
            throw new Exception(errorMessage);
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
            // ignore
        }
    }
    return result;
}

From source file:setiquest.renderer.Utils.java

/**
 * Send a BSON file./*from   ww w .j  a  va 2s .  c  o  m*/
 * @param filename the full path to the BSON file.
 * @param actId the activity Id.
 * @param obsId the observation Id.
 * @param pol the POL of thedata.
 * @param subchannel the subchannel of the data.
 */
public static String sendBSONFile(String filename, int actId, int obsId, int pol, String subchannel) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Utils.getSubjectsURL());

    Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:"
            + subchannel);

    FileBody bin = new FileBody(new File(filename));
    try {
        StringBody comment = new StringBody("Filename: " + filename);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", bin);
        reqEntity.addPart("type", new StringBody("data/bson"));
        reqEntity.addPart("subject[activity_id]", new StringBody("" + actId));
        reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId));
        reqEntity.addPart("subject[pol]", new StringBody("" + pol));
        reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel));
        httppost.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        Log.log(response.toString());
        return response.toString();

        /*
           sendResult  = "subject[activity_id]: " + actId + "\n";
           sendResult += "subject[observation_id]: " + obsId + "\n";
           sendResult += "subject[pol]: " + pol + "\n";
           sendResult += "subject[subchannel]: " + subchannel + "\n";
           sendResult += response.toString() + "|\n";
           */

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "ERROR";
}