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:palamarchuk.smartlife.app.fragments.ProfileFragment.java

private void attachCardQuery(String cardNumber, String cardPin) {

    final QueryMaster.OnCompleteListener onCompleteListener = new QueryMaster.OnCompleteListener() {
        @Override/*  w  w  w. ja  v a 2s . c om*/
        public void complete(String serverResponse) {
            //                QueryMaster.alert(getActivity(), serverResponse);
            try {
                JSONObject json = new JSONObject(serverResponse);
                if (QueryMaster.isSuccess(json)) {
                    FragmentHelper.updateFragment(getFragmentManager());

                    QueryMaster.alert(getActivity(), R.string.bonuses_was_added_from_card);

                } else {
                    QueryMaster.toast(getActivity(), json.getString("message"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                QueryMaster.alert(getActivity(), QueryMaster.SERVER_RETURN_INVALID_DATA);
            }
        }

        @Override
        public void error(int errorCode) {
            QueryMaster.alert(getActivity(), QueryMaster.ERROR_MESSAGE);
        }
    };

    MultipartEntity entity = new MultipartEntity();

    try {
        entity.addPart("card_number", new StringBody(cardNumber));
        entity.addPart("pin", new StringBody(cardPin));
        entity.addPart("token", new StringBody(((FragmentHolderActivity) getActivity()).getDeviceToken()));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    QueryMaster queryMaster = new QueryMaster(getActivity(), ServerRequest.ATTACH_CARD, QueryMaster.QUERY_POST,
            entity);

    queryMaster.setProgressDialog();
    queryMaster.setOnCompleteListener(onCompleteListener);

    queryMaster.start();
}

From source file:com.jaeksoft.searchlib.Monitor.java

private final void addIfNotNull(MultipartEntity reqEntity, String name, String value)
        throws UnsupportedEncodingException {
    if (value == null)
        return;/*from  ww  w.j  a  v a2s .  co m*/
    reqEntity.addPart(name.replace('.', '_'), new StringBody(value));
}

From source file:org.openbmap.soapclient.AsyncUploader.java

/**
 * Sends an authenticated http post request to upload file
 * @param file File to upload (full path)
 * @return true on response code 200, false otherwise
 *///from w w  w.ja  v a 2s. c  o m
private UploadResult httpPostRequest(final String file) {
    // TODO check network state
    // @see http://developer.android.com/training/basics/network-ops/connecting.html

    // Adjust HttpClient parameters
    final HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    // HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    final HttpPost httppost = new HttpPost(mServer);
    try {
        final MultipartEntity entity = new MultipartEntity();
        entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml"));

        if ((mUser != null) && (mPassword != null)) {
            final String authorizationString = "Basic "
                    + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP);
            httppost.setHeader("Authorization", authorizationString);
        }

        if (mToken != null) {
            entity.addPart(API_FIELD, new StringBody(mToken));
        }

        httppost.setEntity(entity);
        final HttpResponse response = httpclient.execute(httppost);

        final int reply = response.getStatusLine().getStatusCode();
        if (reply == 200) {
            // everything is ok if we receive HTTP 200
            mSize = entity.getContentLength();
            Log.i(TAG, "Uploaded " + file + ": Server reply " + reply);
            return UploadResult.OK;
        } else if (reply == 401) {
            Log.e(TAG, "Wrong username or password");
            return UploadResult.WRONG_PASSWORD;
        } else {
            Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply);
            return UploadResult.ERROR;
        }
        // TODO: redirects (301, 302) are NOT handled here
        // thus if something changes on the server side we're dead here
    } catch (final ClientProtocolException e) {
        Log.e(TAG, e.getMessage());
    } catch (final IOException e) {
        Log.e(TAG, "I/O exception on file " + file);
    }
    return UploadResult.UNDEFINED;
}

From source file:org.eclipse.egit.github.core.service.DownloadService.java

/**
 * Upload a resource to be available as the download described by the given
 * resource.//w  w w. j a  v a 2  s . c  o  m
 *
 * @param resource
 * @param content
 * @param size
 * @throws IOException
 */
public void uploadResource(DownloadResource resource, InputStream content, long size) throws IOException {
    if (resource == null)
        throw new IllegalArgumentException("Download resource cannot be null"); //$NON-NLS-1$
    if (content == null)
        throw new IllegalArgumentException("Content input stream cannot be null"); //$NON-NLS-1$

    HttpClient client = createDownloadClient();

    HttpPost post = new HttpPost(resource.getS3Url());
    MultipartEntity entity = new MultipartEntity();
    entity.addPart(UPLOAD_KEY, new StringBody(resource.getPath()));
    entity.addPart(UPLOAD_ACL, new StringBody(resource.getAcl()));
    entity.addPart(UPLOAD_SUCCESS_ACTION_STATUS, new StringBody(Integer.toString(HttpStatus.SC_CREATED)));
    entity.addPart(UPLOAD_FILENAME, new StringBody(resource.getName()));
    entity.addPart(UPLOAD_AWS_ACCESS_KEY_ID, new StringBody(resource.getAccesskeyid()));
    entity.addPart(UPLOAD_POLICY, new StringBody(resource.getPolicy()));
    entity.addPart(UPLOAD_SIGNATURE, new StringBody(resource.getSignature()));
    entity.addPart(HttpHeaders.CONTENT_TYPE, new StringBody(resource.getMimeType()));
    entity.addPart(UPLOAD_FILE, new SizedInputStreamBody(content, size));
    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_CREATED)
        throw new IOException("Unexpected response status of " + status); //$NON-NLS-1$
}

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 ww. j  ava  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:com.impetus.ankush.agent.action.impl.UploadHandler.java

/**
 * Method that builds the multi-part form data request.
 * // ww w .  j  a v a 2  s . c o m
 * @param urlString
 *            the urlString to which the file needs to be uploaded
 * @param file
 *            the actual file instance that needs to be uploaded
 * @param fileName
 *            name of the file, just to show how to add the usual form
 *            parameters
 * @param fileDescription
 *            some description for the file, just to show how to add the
 *            usual form parameters
 * @return server response as <code>String</code>
 */
public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {

    HttpPost postRequest = new HttpPost(urlString);
    try {

        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // The usual form parameters can be added this way
        multiPartEntity.addPart("fileDescription",
                new StringBody(fileDescription != null ? fileDescription : ""));
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));

        /*
         * Need to construct a FileBody with the file that needs to be
         * attached and specify the mime type of the file. Add the fileBody
         * to the request as an another part. This part will be considered
         * as file part and the rest of them as usual form-data parts
         */
        FileBody fileBody = new FileBody(file, "application/octect-stream");
        multiPartEntity.addPart("file", fileBody);

        postRequest.setEntity(multiPartEntity);

    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return null;
    }

    return executeRequest(postRequest);
}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * @param image//from  w w  w .  j a v a2  s .  co  m
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws UnsupportedEncodingException
 */
private String getAsciiArt(BufferedImage image)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    File tmpfile = File.createTempFile("bjint_", ".jpg");
    ImageIO.write(image, "jpg", tmpfile);

    // http://picascii.com/????
    // ?????
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://picascii.com/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    entity.consumeContent();

    // ???
    HttpPost httppost = new HttpPost("http://picascii.com/upload.php");
    //HttpPost httppost = buildDefaultHttpMessage(new HttpPost("http://localhost:8080/sa-struts-tutorial/upload/"));

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody bin = new FileBody(tmpfile, "image/jpeg");
    reqEntity.addPart("imageupload", bin);
    reqEntity.addPart("MAX_FILE_SIZE", new StringBody("1000000"));
    reqEntity.addPart("url", new StringBody(""));
    reqEntity.addPart("quality", new StringBody("3"));
    reqEntity.addPart("size", new StringBody("1"));

    httppost.setEntity(reqEntity);

    response = httpclient.execute(httppost);
    String responseHtml = IOUtils.toString(response.getEntity().getContent());

    httpclient.getConnectionManager().shutdown();

    // tmpFile?
    tmpfile.delete();
    return bringOutAsciiArtString(responseHtml);
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testMultipartPostWithoutParameters() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart");
    MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT);
    multipart.addPart("part1", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    multipart.addPart("part2", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8")));
    post.setEntity(multipart);/*  w w w .j a  v a 2s  .c o  m*/
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testMultipartPostWithParametersAndPayload() throws Exception {
    HttpPost post = new HttpPost(
            "http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/123?query=abcd");
    MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT);
    multipart.addPart("part1", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    multipart.addPart("part2", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8")));
    post.setEntity(multipart);/*w w w  . j av a 2 s  .  c  o  m*/
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.wialon.remote.ApacheSdkHttpClient.java

@Override
public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) {
    try {/*from  w  w  w. j  a  va 2  s  . c  o m*/
        HttpPost httpPost = new HttpPost(url);
        MultipartEntity multipartEntity = new MultipartEntity();
        if (params != null)
            for (Map.Entry<String, String> entry : params.entrySet())
                multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
        multipartEntity.addPart("file", new FileBody(file));
        httpPost.setEntity(multipartEntity);
        sendRequest(getHttpClient(timeout), httpPost, callback);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        callback.error = e;
        callback.done(null);
    }
}