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.onesite.commons.net.http.rest.client.RestClient.java

/**
 * Create a POST request to the given url posting the ContentBody to the content tag
 * URL = scheme://host:port/path?query_string
 * /*w ww .  j a  v a  2s .  c  o m*/
 * @param path
 * @param params
 * @param body
 * @return
 * @throws Exception
 */
public int post(String path, Map<String, String> params, ContentBody body) throws Exception {
    String url = this.generateEncodeURLString(path, params);

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpPost request = new HttpPost(url);
    request.addHeader("accept", "application/json");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("content", body);
    request.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(this.target, request);

        try {
            this.processHttpResponse(response);
        } catch (Exception e) {
            log.error("Error processing HttpResponse from " + url);
            throw e;
        }
    } catch (Exception e) {
        log.error("Error occurred during calling to " + url);
        throw e;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return status;
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {/* w  ww.j a v  a 2 s  . co m*/

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(
                new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUploadWithEagerParsing() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {/*from ww  w . j a  va 2  s  .c  om*/

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(
                new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.ubicompforall.BusTUC.Speech.HTTP.java

public DummyObj sendPost(String filePath, Context context, double lat, double lon) {
    String response = "Fant ikke noe";
    long first = System.nanoTime();
    Calc calc = new Calc();
    DummyObj dummy = new DummyObj();
    HttpClient httpclient = new DefaultHttpClient();
    long second = System.nanoTime() - first;
    //   File file = new File(Environment.getExternalStorageDirectory(),
    //      filePath);
    File file = new File(filePath);
    HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst");
    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String t_id = tm.getDeviceId();
    String tmp = "TABuss";
    String p_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    try {//from ww  w . jav  a  2s .  c  om
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("lat", new StringBody(String.valueOf(lat)));
        entity.addPart("lon", new StringBody(String.valueOf(lon)));
        entity.addPart("devID", new StringBody(tmp + p_id));
        entity.addPart("speechinput", new FileBody(file, "multipart/form-data;charset=\"UTF-8\""));

        httppost.setEntity(entity);
        response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8");
        System.out.println("RESPONSE: " + response);
        dummy = calc.parse(response);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
    return dummy;

}

From source file:edu.scripps.fl.pubchem.web.session.WebSessionBase.java

protected MultipartEntity addParts(MultipartEntity entity, Object... pairs)
        throws UnsupportedEncodingException {
    for (int ii = 0; ii < pairs.length; ii += 2)
        entity.addPart(pairs[ii].toString(), new StringBody(pairs[ii + 1].toString()));
    return entity;
}

From source file:org.fabrician.maven.plugins.GridlibUploadMojo.java

public void execute() throws MojoExecutionException {
    String username = brokerUsername;
    String password = brokerPassword;
    if (serverId != null && !"".equals(serverId)) {
        // TODO: implement server_id
        throw new MojoExecutionException("serverId is not yet supported");
    } else if (brokerUsername == null || "".equals(brokerUsername) || brokerPassword == null
            || "".equals(brokerPassword)) {
        throw new MojoExecutionException("serverId or brokerUsername and brokerPassword must be set");
    }//from  w  ww. j  av a2 s .co  m

    DirectoryScanner ds = new DirectoryScanner();
    ds.setIncludes(mIncludes);
    ds.setExcludes(mExcludes);
    ds.setBasedir(".");
    ds.setCaseSensitive(true);
    ds.scan();

    String[] files = ds.getIncludedFiles();
    if (files == null) {
        getLog().info("No files found to upload");
    } else {
        getLog().info("Found " + files.length + " file to upload");

        for (String file : files) {
            File gridlibFilename = new File(file);
            getLog().info("Uploading " + gridlibFilename + " to " + brokerUrl);

            DefaultHttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            Credentials cred = new UsernamePasswordCredentials(username, password);
            httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, cred);

            try {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("gridlibOverwrite",
                        new StringBody(String.valueOf(gridlibOverwrite), Charset.forName("UTF-8")));
                entity.addPart("gridlibArchive", new FileBody(gridlibFilename));

                HttpPost method = new HttpPost(brokerUrl);
                method.setEntity(entity);

                HttpResponse response = httpclient.execute(method);
                StatusLine status = response.getStatusLine();
                int code = status.getStatusCode();
                if (code >= 400 && code <= 500) {
                    throw new MojoExecutionException(
                            "Failed to upload " + gridlibFilename + " to " + brokerUrl + ": " + code);
                }
            } catch (Exception e) {
                throw new MojoExecutionException(e.getMessage());
            }
        }
    }
}

From source file:fedroot.dacs.http.DacsPostRequest.java

/**
 * this is a "hybrid" multipart/form-data with parameters passed in the query string
 * and only file(s) included in the multipart entity
 * @param webServiceRequest/*from  w  w w  . j  a  v a  2 s . c  o m*/
 * @return
 */
private HttpPost multipartPost(WebServiceRequest webServiceRequest) {
    HttpPost multipartPost = new HttpPost(webServiceRequest.getURI());
    MultipartEntity multipartEntity = new MultipartEntity();

    for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) {
        multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody());
    }
    multipartPost.setEntity(multipartEntity);
    return multipartPost;
}

From source file:ca.mcgill.hs.uploader.UploadThread.java

/**
 * Executes the upload in a separate thread
 *//* ww w. j a va2 s. co m*/

@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:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox./*  w w w.  j av a2s.c  o  m*/
 */
public void put(String to, ContentBody content) throws IOException {
    HttpClient client = getClient();

    HttpPost req = (HttpPost) buildRequest(HttpPost.METHOD_NAME, "/files/" + ROOT + to, true);

    // this has to be done this way because of how oauth signs params
    // first we add a "fake" param of file=path of *uploaded* file, THEN we sign that.
    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("file", content.getFilename()));
    req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    try {
        auth.sign(req);
    } catch (OAuthException e) {
        IOException failure = new IOException(e.getMessage());
        failure.initCause(e);
        throw failure;
    }
    // now we can add the real file multipart and we're good
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("file", content);

    // this resets it to the new entity with the real file
    req.setEntity(entity);

    this.finish(client.execute(req));
}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v1.VisualRecognition.java

/**
 * Classifies the images against the label groups and labels. The response
 * includes a score for a label if the score meets the minimum threshold of
 * 0.5. If no score meets the threshold for an image, no labels are
 * returned.//from   w ww .j a v a 2  s  .  c  o m
 * 
 * @param image
 *            the file image
 * @param labelSet
 *            the labels to classify against
 * @return the visual recognition images
 */
public RecognizedImage recognize(final File image, final LabelSet labelSet) {
    if (image == null)
        throw new IllegalArgumentException("image can not be null");
    try {

        Request request = Request.Post("/v1/tag/recognize");

        MultipartEntity reqEntity = new MultipartEntity();

        // Set the image_file
        FileBody bin = new FileBody(image);
        reqEntity.addPart(IMG_FILE, bin);

        if (labelSet != null) {
            StringBody labels = new StringBody(GsonSingleton.getGson().toJson(labelSet),
                    Charset.forName("UTF-8"));

            // Set the labels_to_check
            reqEntity.addPart(LABELS_TO_CHECK, labels);
        }
        request.withEntity(reqEntity);

        HttpResponse response = execute(request.build());
        String resultJson = ResponseUtil.getString(response);
        VisualRecognitionImages recognizedImages = GsonSingleton.getGson().fromJson(resultJson,
                VisualRecognitionImages.class);
        return recognizedImages.getImages().get(0);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}