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:org.dataconservancy.ui.it.support.MetadataFileRequest.java

public HttpPost asHttpPost() {

    String depositUrl = urlConfig.getMetadataFileUrl().toString();
    HttpPost post = new HttpPost(depositUrl);
    MultipartEntity entity = new MultipartEntity();
    try {/* w  ww  .j a v  a  2  s.c om*/
        entity.addPart("parentID", new StringBody(parentId, Charset.forName("UTF-8")));
        if (name != null && !name.isEmpty()) {
            entity.addPart("metadataFile.name", new StringBody(name, Charset.forName("UTF-8")));
        }

        if (metadataFormat != null && !metadataFormat.isEmpty()) {
            entity.addPart("metadataFile.metadataFormatId",
                    new StringBody(metadataFormat, Charset.forName("UTF-8")));
        }

        if (id != null && !id.isEmpty()) {
            entity.addPart("metadataFileID", new StringBody(id, Charset.forName("UTF-8")));
        }

        if (isCollection) {
            entity.addPart("redirectUrl", new StringBody("viewCollectionDetails", Charset.forName("UTF-8")));
        }

        entity.addPart(event, new StringBody(event, Charset.forName("UTF-8")));

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (fileToDeposit != null) {
        FileBody fileBody = new FileBody(fileToDeposit);
        entity.addPart("uploadedFile", fileBody);
        post.setEntity(entity);
    }
    return post;
}

From source file:com.captchatrader.CaptchaTrader.java

/**
 * Responds if an CAPTCHA wes correctly answered or not
 * /*from w w  w .ja  va2s  .c o m*/
 * @param captcha
 *            the CAPTCHA object
 * @param state
 *            <code>true</code> if the CAPTCHA was correctly resolved
 * @throws CaptchaTraderException
 *             any of the possible errors
 */
public void respond(ResolvedCaptcha captcha, boolean state) throws CaptchaTraderException, IOException {
    final URI requestUri = apiURI.resolve("respond");
    final HttpPost request = new HttpPost(requestUri);
    final MultipartEntity entity = new MultipartEntity();

    entity.addPart("is_correct", new StringBody(state ? "1" : "0"));
    entity.addPart("password", new StringBody(password));
    entity.addPart("ticket", new StringBody(captcha.getID()));
    entity.addPart("username", new StringBody(username));

    request.setEntity(entity);
    validate(execute(request));
}

From source file:com.liferay.arquillian.container.LiferayContainer.java

private MultipartEntity createMultipartEntity(Archive<?> archive) {
    ZipExporter zipView = archive.as(ZipExporter.class);

    InputStream inputStream = zipView.exportAsInputStream();

    MultipartEntity entity = new MultipartEntity();

    entity.addPart(archive.getName(), new InputStreamBody(inputStream, archive.getName()));
    return entity;
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

public MultipartEntity createMultipartEntity(FileBody fileBody, String mimeType, int sampleRate) {
    // see: http://stackoverflow.com/questions/3014633
    //MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);

    try {// w  w  w . j  a v a  2 s  . co m
        entity.addPart("email", new StringBody(mEmail, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("MODEL_SAMPLE_RATE",
                new StringBody(String.valueOf(sampleRate), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("DECODING", new StringBody(mDecodingSpeed, "text/plain", Charset.forName("UTF-8")));
        String sendEmailAsString = "0";
        if (mIsSendEmail) {
            sendEmailAsString = "1";
        }
        entity.addPart("SEND_EMAIL", new StringBody(sendEmailAsString, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("upload_wav", fileBody);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return entity;
}

From source file:de.xwic.appkit.core.remote.client.MultipartRequestHelper.java

/**
 * @param entity/*from w w  w  .ja v  a  2s.  c  o m*/
 * @param config
 * @throws UnsupportedEncodingException
 */
public MultipartRequestHelper(final MultipartEntity entity, final RemoteSystemConfiguration config)
        throws UnsupportedEncodingException {
    targetUrl = config.getRemoteBaseUrl() + config.getApiSuffix();
    entity.addPart(RemoteDataAccessServlet.PARAM_RSID, new StringBody(config.getRemoteSystemId()));

    IUser currentUser = DAOSystem.getSecurityManager().getCurrentUser();
    if (currentUser != null) {
        entity.addPart(RemoteDataAccessServlet.PARAM_USERNAME, new StringBody(currentUser.getLogonName()));
    }

    this.entity = entity;

}

From source file:com.captchatrader.CaptchaTrader.java

/**
 * Submit a CAPTCHA already hosted on an existing website.
 * /*from ww  w.  j  a  va2  s. c  o  m*/
 * @param uri
 *            The URI of the CAPTCHA image.
 * @return The decoded CAPTCHA.
 * @throws Any
 *             exceptions sent by the server.
 */
public ResolvedCaptcha submit(URI uri) throws CaptchaTraderException, IOException {
    final URI requestUri = apiURI.resolve("submit");
    final HttpPost request = new HttpPost(requestUri);
    final MultipartEntity entity = new MultipartEntity();

    entity.addPart("api_key", new StringBody(applicationKey));
    entity.addPart("username", new StringBody(username));
    entity.addPart("password", new StringBody(password));
    entity.addPart("value", new StringBody(uri.toString()));

    request.setEntity(entity);
    final List<Object> response = validate(execute(request));

    return new ResolvedCaptcha(this, ((Long) response.get(0)).toString(), (String) response.get(1));
}

From source file:net.yama.android.managers.connection.OAuthConnectionManager.java

/**
 * Special request for photo upload since OAuth doesn't handle multipart/form-data
 *//*from   ww w  .j ava2s. co  m*/
public String uploadPhoto(WritePhotoRequest request) throws ApplicationException {

    String responseString = null;
    try {
        OAuthAccessor accessor = new OAuthAccessor(OAuthConnectionManager.consumer);
        accessor.accessToken = ConfigurationManager.instance.getAccessToken();
        accessor.tokenSecret = ConfigurationManager.instance.getAccessTokenSecret();

        String tempImagePath = request.getParameterMap().remove(Constants.TEMP_IMAGE_FILE_PATH);
        String eventId = request.getParameterMap().remove(Constants.EVENT_ID_KEY);

        ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>();
        convertRequestParamsToOAuth(params, request.getParameterMap());
        OAuthMessage message = new OAuthMessage(request.getMethod(), request.getRequestURL(), params);
        message.addRequiredParameters(accessor);
        List<Map.Entry<String, String>> oAuthParams = message.getParameters();
        String url = OAuth.addParameters(request.getRequestURL(), oAuthParams);

        HttpPost post = new HttpPost(url);
        File photoFile = new File(tempImagePath);
        FileBody photoContentBody = new FileBody(photoFile);
        StringBody eventIdBody = new StringBody(eventId);

        HttpClient client = new DefaultHttpClient();
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        reqEntity.addPart(Constants.PHOTO, photoContentBody);
        reqEntity.addPart(Constants.EVENT_ID_KEY, eventIdBody);
        post.setEntity(reqEntity);

        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        responseString = EntityUtils.toString(resEntity);

    } catch (Exception e) {
        Log.e("OAuthConnectionManager", "Exception in uploadPhoto()", e);
        throw new ApplicationException(e);
    }

    return responseString;
}

From source file:com.revo.deployr.client.call.repository.RepositoryFileUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *//*from w  w w .ja v  a 2  s  . c o m*/
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        if (options.filename != null)
            entity.addPart("filename",
                    new StringBody(options.filename, "text/plain", Charset.forName("UTF-8")));
        if (options.directory != null)
            entity.addPart("directory",
                    new StringBody(options.directory, "text/plain", Charset.forName("UTF-8")));
        if (options.descr != null)
            entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("newversion",
                new StringBody(Boolean.toString(options.newversion), "text/plain", Charset.forName("UTF-8")));
        if (options.newversionmsg != null)
            entity.addPart("newversionmsg",
                    new StringBody(options.newversionmsg, "text/plain", Charset.forName("UTF-8")));
        if (options.restricted != null)
            entity.addPart("restricted",
                    new StringBody(options.restricted, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("shared",
                new StringBody(Boolean.toString(options.shared), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("published",
                new StringBody(Boolean.toString(options.published), "text/plain", Charset.forName("UTF-8")));
        if (options.inputs != null)
            entity.addPart("inputs", new StringBody(options.inputs, "text/plain", Charset.forName("UTF-8")));
        if (options.outputs != null)
            entity.addPart("outputs", new StringBody(options.outputs, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("RepositoryFileUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("RepositoryFileUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:webcamcapture.WebCamCapture.java

void request(String url, String file_name) throws IOException {
    try {//from   www  .ja va  2 s  .  com
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(url);

        String file_path = "C:/Users/darshit/Documents/NetBeansProjects/WebCamCapture/" + file_name;
        File fileToUse = new File(file_path);
        FileBody data = new FileBody(fileToUse, "image/jpeg");

        System.out.println(Inet4Address.getLocalHost().getHostAddress());
        /*MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(fileToUse, "image/jpeg");
        mpEntity.addPart("userfile", cbFile);*/

        // httppost.setEntity(mpEntity);
        //String file_type = "JPG" ;

        MultipartEntity reqEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(fileToUse, "image/jpeg");
        reqEntity.addPart("file", data);

        //reqEntity.addPart("file", cbFile);

        httppost.setEntity(reqEntity);
        //httppost.setEntity(mpEntity); 
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStreamReader is;

        StringBuffer sb = new StringBuffer();
        System.out.println("finalResult " + sb.toString());
        //String line=null;
        /*while((reader.readLine())!=null){
        sb.append(line + "\n");
        }*/

        //StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = sb.toString();
        System.out.println("finalResult " + sb.toString());
        // System.out.println( response ); 
        // String responseString = new BasicResponseHandler().handleResponse(response);
        //System.out.println();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(httpRequestSend.class.getName()).log(Level.SEVERE, null, ex);
        System.out.printf("dsf\n");
    }
}

From source file:org.eclipse.cbi.maven.plugins.winsigner.SignMojo.java

/**
 * helper to send the file to the signing service
 * @param source file to send//from ww w.j av  a2s .c om
 * @param target file to copy response to
 * @throws IOException
 * @throws MojoExecutionException
 */
private void postFile(File source, File target) throws IOException, MojoExecutionException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(signerUrl);

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("file", new FileBody(source));
    post.setEntity(reqEntity);

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

    HttpEntity resEntity = response.getEntity();
    if (statusCode >= 200 && statusCode <= 299 && resEntity != null) {
        InputStream is = resEntity.getContent();
        try {
            FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target);
        } finally {
            IOUtil.close(is);
        }
    } else {
        throw new MojoExecutionException("Signer replied " + response.getStatusLine());
    }
}