Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

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

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:net.yacy.grid.http.ClientConnection.java

/**
 * POST request//  www  . ja  v  a2 s .  c  om
 * @param urlstring
 * @param map
 * @param useAuthentication
 * @throws ClientProtocolException 
 * @throws IOException
 */
public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication)
        throws ClientProtocolException, IOException {
    this.request = new HttpPost(urlstring);
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (Map.Entry<String, byte[]> entry : map.entrySet()) {
        entityBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }
    ((HttpPost) this.request).setEntity(entityBuilder.build());
    this.request.setHeader("User-Agent",
            ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    this.init();
}

From source file:com.servoy.extensions.plugins.http.BaseEntityEnclosingRequest.java

@Override
protected HttpEntity buildEntity() throws Exception {
    HttpEntity entity = null;/* w  w  w .  j  a v  a 2  s .co m*/
    if (files.size() == 0) {
        if (params != null) {
            entity = new UrlEncodedFormEntity(params, charset);
        } else if (!Utils.stringIsEmpty(content)) {
            entity = new StringEntity(content, mimeType, charset);
            content = null;
        }
    } else if (files.size() == 1 && (params == null || params.size() == 0)) {
        Object f = files.values().iterator().next();
        if (f instanceof File) {
            entity = new FileEntity((File) f, ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else if (f instanceof JSFile) {
            entity = new InputStreamEntity(((JSFile) f).getAbstractFile().getInputStream(),
                    ((JSFile) f).js_size(), ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else {
            Debug.error("could not add file to post request unknown type: " + f);
        }
    } else {
        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        for (Entry<Pair<String, String>, Object> e : files.entrySet()) {
            Object file = e.getValue();
            if (file instanceof File) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new FileBody((File) file));
            } else if (file instanceof JSFile) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(),
                        new ByteArrayBody(
                                Utils.getBytesFromInputStream(
                                        ((JSFile) file).getAbstractFile().getInputStream()),
                                "binary/octet-stream", ((JSFile) file).js_getName()));
            } else {
                Debug.error("could not add file to post request unknown type: " + file);
            }
        }

        // add the parameters
        if (params != null) {
            Iterator<NameValuePair> it = params.iterator();
            while (it.hasNext()) {
                NameValuePair nvp = it.next();
                // For usual String parameters
                ((MultipartEntity) entity).addPart(nvp.getName(),
                        new StringBody(nvp.getValue(), "text/plain", Charset.forName(charset)));
            }
        }
    }

    // entity may have been set already, see PutRequest.js_setFile
    return entity;
}

From source file:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox.//from w  w w . ja  v a  2  s. co 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:eu.liveandgov.ar.utilities.OS_Utils.java

/**
 * Remotely recognize captured image//from   w  w w . j av a 2s. c  o m
 * 
 * @param url
 * @param nameValuePairs
 */
public static HttpResponse remote_rec(String url, List<NameValuePair> nameValuePairs, Context ctx) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (int index = 0; index < nameValuePairs.size(); index++) {

            if (nameValuePairs.get(index).getName().equalsIgnoreCase("upload"))
                entity.addPart("upload", new FileBody(new File(nameValuePairs.get(index).getValue())));
            else
                entity.addPart(nameValuePairs.get(index).getName(),
                        new StringBody(nameValuePairs.get(index).getValue()));
        }

        httpPost.setEntity(entity);
        HttpResponse httpresponse = httpClient.execute(httpPost, localContext);

        return httpresponse;

    } catch (Exception e) {
        //Toast.makeText(ctx, "Can not send for recognition. Internet accessible?", Toast.LENGTH_LONG).show();
        Log.e("ERROR", "Can not send for recognition. Internet accessible?");
        return null;
    }

}

From source file:com.siahmsoft.soundroid.sdk7.services.UploadService.java

public void uploadTrack(Bundle bundle) {

    Track track = TracksStore.Track.fromBundle(bundle);
    //SystemClock.sleep(1500);

    if (track.getmIdTrack() == 0) {

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName(HTTP.UTF_8));

        try {/*w ww  . ja  v a 2s. co  m*/

            if (track.getmTrackPath() != null && !"".equals(track.getmTrackPath())) {
                ContentBody asset_Data = new FileBody(new File(track.getmTrackPath()));
                entity.addPart("track[asset_data]", asset_Data);
            }

            if (track.getmArtworkPath() != null && !"".equals(track.getmArtworkPath())) {
                ContentBody artworkData = new FileBody(new File(track.getmArtworkPath()));
                entity.addPart("track[artwork_data]", artworkData);
            }

            if (track.getmTitle() != null && !"".equals(track.getmTitle())) {
                entity.addPart("track[title]", new StringBody(track.getmTitle()));
            }

            if (track.getmDescription() != null && !"".equals(track.getmDescription())) {
                entity.addPart("track[description]", new StringBody(track.getmDescription()));
            }

            if (track.getmDownloadable() != null && !"".equals(track.getmDownloadable())) {
                entity.addPart("track[downloadable]", new StringBody(track.getmDownloadable()));
            }

            if (track.getmSharing() != null && !"".equals(track.getmSharing())) {
                entity.addPart("track[sharing]", new StringBody(track.getmSharing()));
            }

            if (!"".equals(track.getmBpm())) {
                entity.addPart("track[bpm]", new StringBody(String.valueOf(track.getmBpm())));
            }

            if (track.getmTagList() != null && !"".equals(track.getmTagList())) {
                entity.addPart("track[tag_list]", new StringBody(track.getmTagList()));
            }

            if (track.getmGenre() != null && !"".equals(track.getmGenre())) {
                entity.addPart("track[genre]", new StringBody(track.getmGenre()));
            }

            if (track.getmLicense() != null && !"".equals(track.getmLicense())) {
                entity.addPart("track[license]", new StringBody(track.getmLicense()));
            }

            if (track.getmLabelName() != null && !"".equals(track.getmLabelName())) {
                entity.addPart("track[label_name]", new StringBody(track.getmLabelName()));
            }

            if (track.getmTrackType() != null && !"".equals(track.getmTrackType())) {
                entity.addPart("track[track_type]", new StringBody(track.getmTrackType()));
            }

            HttpPost filePost = new HttpPost("http://api.soundcloud.com/tracks");
            Soundroid.getSc().signRequest(filePost);
            filePost.setEntity(entity);

            try {
                //SystemClock.sleep(1000);
                showNotification("Uploading track " + track.getmTitle());
                final HttpResponse response = sClient.execute(filePost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                    showNotification("Track " + track.getmTitle() + " uploaded");
                    sClient.getConnectionManager().closeExpiredConnections();
                    totalUploads--;
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {

        }
    } else {//Edicin de la cancin

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName(HTTP.UTF_8));
        try {

            if (track.getmTrackPath() != null && !"".equals(track.getmTrackPath())) {
                ContentBody asset_Data = new FileBody(new File(track.getmTrackPath()));
                entity.addPart("track[asset_data]", asset_Data);
            }

            if (track.getmArtworkPath() != null && !"".equals(track.getmArtworkPath())) {
                ContentBody artworkData = new FileBody(new File(track.getmArtworkPath()));
                entity.addPart("track[artwork_data]", artworkData);
            }

            if (track.getmTitle() != null) {
                entity.addPart("track[title]", new StringBody(track.getmTitle()));
            }

            if (track.getmDescription() != null) {
                entity.addPart("track[description]", new StringBody(track.getmDescription()));
            }

            if (track.getmDownloadable() != null) {
                entity.addPart("track[downloadable]", new StringBody(track.getmDownloadable()));
            }

            if (track.getmSharing() != null) {
                entity.addPart("track[sharing]", new StringBody(track.getmSharing()));
            }

            entity.addPart("track[bpm]", new StringBody(String.valueOf(track.getmBpm())));

            if (track.getmTagList() != null) {
                entity.addPart("track[tag_list]", new StringBody(track.getmTagList()));
            }

            if (track.getmGenre() != null) {
                entity.addPart("track[genre]", new StringBody(track.getmGenre()));
            }

            if (track.getmLicense() != null) {
                entity.addPart("track[license]", new StringBody(track.getmLicense()));
            }

            if (track.getmLabelName() != null) {
                entity.addPart("track[label_name]", new StringBody(track.getmLabelName()));
            }

            if (track.getmTrackType() != null) {
                entity.addPart("track[track_type]", new StringBody(track.getmTrackType()));
            }

            HttpPut filePut = new HttpPut("http://api.soundcloud.com/tracks/" + track.getmIdTrack() + ".json");
            Soundroid.getSc().signRequest(filePut);

            filePut.setEntity(entity);

            try {
                //SystemClock.sleep(1000);
                showNotification("Uploading track " + track.getmTitle());
                final HttpResponse response = sClient.execute(filePut);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                    showNotification("Track " + track.getmTitle() + " edited");
                    sClient.getConnectionManager().closeExpiredConnections();
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {

        }
    }
}

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

@Override
public void processNZB(NZB nzb) throws RetrieveException {
    try {/*from ww w . ja  v  a2  s.c  om*/
        login();
        List<NameValuePair> fields = null;
        String command = null;
        if (useReportId(nzb)) {
            fields = getReportIdProps(nzb);
            command = getReportIdCommand();
        } else if (useUrl(nzb)) {
            fields = getUrlProps(nzb);
            command = getUrlCommand();
        }
        if (fields != null) {
            //Do the request            
            HttpResponse response = null;
            try {
                response = doGet(command, fields);
                validateResponse(response.getEntity().getContent());
            } finally {
                if (response != null) {
                    response.getEntity().consumeContent();
                }
            }
        } else { // no url or reportId
            //post file using POST
            fields = getFilepostOtherProps(nzb);
            command = getFilepostCommand();
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            ContentBody cb = new InputStreamBody(new ByteArrayInputStream(nzb.getData()), nzb.getFilename());
            entity.addPart(getFilepostField(), cb);
            HttpResponse response = null;
            try {
                response = doPost(command, fields, entity);
                validateResponse(response.getEntity().getContent());
            } finally {
                if (response != null) {
                    response.getEntity().consumeContent();
                }
            }
        }
        logout();
    } catch (IOException e) {
        throw new RetrieveException("Error posting nzb file", e);
    }
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//from w  ww. j  a v a  2s  .  co  m
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

public void addMultiPartPostParam(String key, ContentBody contentBody) {
    if (multipartEntity == null) {
        multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    }//from  ww w . ja v a 2 s  .c  o  m
    multipartEntity.addPart(key, contentBody);
}

From source file:org.hk.jt.client.core.Request.java

private HttpResponse execPost() throws URISyntaxException, InvalidKeyException, UnsupportedEncodingException,
        NoSuchAlgorithmException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpPost httpPost = new HttpPost();
    httpPost.setURI(new URI(requestIf.getUrl()));
    httpPost.setHeader("Authorization", createAuthorizationValue());

    if (postParameter != null && !postParameter.isEmpty()) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : postParameter.keySet()) {
            params.add(new BasicNameValuePair(key, postParameter.get(key)));
        }/*  w w  w . java2s . co m*/
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    }

    if (requestIf.getFiles() != null) {
        final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        List<NameValuePair> fileList = requestIf.getFiles();
        if (fileList != null && !fileList.isEmpty()) {
            for (NameValuePair val : fileList) {
                File file = new File(val.getValue());
                entity.addPart(val.getName(), new FileBody(file, CONTENTTYPE_BINARY));
            }
        }
        httpPost.setEntity(entity);
    }
    httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    return client.execute(httpPost);
}