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:com.google.appinventor.components.runtime.MediaStore.java

/**
 * Asks the Web service to store the given media file.
 *
 * @param mediafile The value to store.//ww  w . jav  a  2  s.c  o  m
 */
@SimpleFunction
public void PostMedia(String mediafile) throws FileNotFoundException {
    AsyncCallbackPair<String> myCallback = new AsyncCallbackPair<String>() {
        public void onSuccess(final String response) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    MediaStored(response);
                }
            });
        }

        public void onFailure(final String message) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    WebServiceError(message);
                }
            });
        }
    };

    try {
        HttpClient client = new DefaultHttpClient();

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        String[] pathtokens = mediafile.split("/");
        String newMediaPath;

        if (pathtokens[0].equals("file:")) {
            newMediaPath = new java.io.File(new URL(mediafile).toURI()).getAbsolutePath();
        } else {
            newMediaPath = mediafile;
        }

        File media = new File(newMediaPath);
        entityBuilder.addPart("file", new FileBody(media));

        HttpEntity entity = entityBuilder.build();

        String uploadURL = getUploadUrl();
        HttpPost post = new HttpPost(uploadURL);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);
        myCallback.onSuccess(result);
    } catch (Exception e) {
        e.printStackTrace();
        myCallback.onFailure(e.getMessage());
    }
}

From source file:ai.susi.server.ClientConnection.java

/**
 * POST request/*www .  j av a  2  s . c o m*/
 * @param urlstring
 * @param map
 * @param useAuthentication
 * @throws ClientProtocolException 
 * @throws IOException
 */
public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication)
        throws ClientProtocolException, IOException {
    this.httpClient = HttpClients.custom().useSystemProperties()
            .setConnectionManager(getConnctionManager(useAuthentication))
            .setDefaultRequestConfig(defaultRequestConfig).build();
    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", USER_AGENT);
    this.init();
}

From source file:Vdisk.java

public void upload_file(String local_filepath, String filepath)
        throws URISyntaxException, FileNotFoundException, IOException {
    File file = new File(local_filepath);
    URI uri = new URIBuilder().setScheme("http").setHost("upload-vdisk.sina.com.cn/2/files/sandbox/")
            .setPath(filepath).setParameter("access_token", this.access_token).build();
    HttpPost httpPost = new HttpPost(uri);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, local_filepath);
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);/*from   w w  w.j av a  2 s .c  o  m*/
    CloseableHttpClient postClient = HttpClients.createDefault();
    try (CloseableHttpResponse response = postClient.execute(httpPost)) {
        System.out.println(response);//check result
    } finally {
        postClient.close();
    }
}

From source file:com.microsoft.cognitive.speakerrecognition.SpeakerRestClientHelper.java

/**
 * Adds a stream to an HTTP entity/*  www  . j  a  v  a2  s.  c  o  m*/
 *
 * @param someStream Input stream to be added to an HTTP entity
 * @param fieldName A description of the entity content
 * @param fileName Name of the file attached as an entity
 * @return HTTP entity
 * @throws IOException Signals a failure while reading the input stream
 */
HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int bytesRead;
    byte[] bytes = new byte[1024];
    while ((bytesRead = someStream.read(bytes)) > 0) {
        byteArrayOutputStream.write(bytes, 0, bytesRead);
    }
    byte[] data = byteArrayOutputStream.toByteArray();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.setStrictMode();
    builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName);
    return builder.build();
}

From source file:com.mobisys.android.ibp.ObservationRequestQueue.java

private void uploadImage(final boolean single, final Bundle b, final Context context,
        final ArrayList<String> imageStringPath, ArrayList<String> imageType, final ObservationInstance sp) {
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (b != null)
        Log.d("ObservationRequestQueue", "Params: " + b.toString());
    int countUri = 0;
    for (int i = 0; i < imageStringPath.size(); i++) {
        if (!imageStringPath.get(i).contains("http://")) {
            FileBody bab;//from  w ww  .  j  a  v a  2 s.  c o m
            if (imageType.get(i) != null)
                bab = new FileBody(new File(imageStringPath.get(i)), imageType.get(i)); // image path and image type
            else
                bab = new FileBody(new File(imageStringPath.get(i)), "image/jpeg"); // image p   
            reqEntity.addPart("resources", bab);

            ++countUri;
        }
    }

    // if imagestring path has no Image url's.
    if (countUri != 0) {
        try {
            reqEntity.addPart(Request.RESOURCE_TYPE, new StringBody("species.participation.Observation"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        WebService.sendMultiPartRequest(context, Request.METHOD_POST, Request.PATH_UPLOAD_RESOURCE,
                new ResponseHandler() {

                    @Override
                    public void onSuccess(String response) {
                        sp.setStatus(StatusType.PROCESSING);
                        ObservationInstanceTable.updateRowFromTable(context, sp);
                        parseUploadResourceDetail(response, single, b, context, sp, imageStringPath);
                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        Log.d("NetWorkState", content);
                        if (e instanceof UnknownHostException || e instanceof ConnectException) {
                            mIsRunning = false;
                            return;
                        }
                        sp.setStatus(StatusType.FAILURE);
                        sp.setMessage(content);
                        ObservationInstanceTable.updateRowFromTable(context, sp);
                        //ObservationParamsTable.deleteRowFromTable(context, sp);
                        if (!single) {
                            ObservationInstance sp_new = ObservationInstanceTable.getFirstRecord(context);
                            observationMethods(single, sp_new, context);
                        }
                    }
                }, reqEntity);

    } else { // if all are url's
        for (int i = 0; i < imageStringPath.size(); i++) {
            b.putString("file_" + (i + 1), imageStringPath.get(i)
                    .replace("http://" + HttpUtils.stageOrProdBaseURL() + "/biodiv/observations/", ""));
            b.putString("type_" + (i + 1), Constants.IMAGE);
            b.putString("license_" + (i + 1), "CC_BY");
        }
        submitObservationRequestFinally(single, b, context, sp);
    }
}

From source file:objective.taskboard.it.TemplateIT.java

private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException {
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA);
    StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA);
    builder.addPart("file", fileBody);
    builder.addPart("name", templateName);
    builder.addPart("roles", roles);
    HttpEntity entity = builder.build();

    HttpPost post = new HttpPost();
    post.setURI(new URI("http://localhost:8900/api/templates"));
    post.setHeaders(session);//from  w  ww.  j  av  a  2s .c om
    post.setEntity(entity);

    return client.execute(post);
}

From source file:net.idea.opentox.cli.dataset.DatasetClient.java

@Override
protected HttpEntity createPOSTEntity(Dataset dataset, List<POLICY_RULE> accessRights)
        throws InvalidInputException, Exception {
    if (dataset.getInputData() == null || dataset.getInputData().getInputFile() == null)
        throw new InvalidInputException("File to import not defined!");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);

    entity.addPart(_WEBFORM.title.name(), new StringBody(dataset.getMetadata().getTitle(), utf8));
    entity.addPart(_WEBFORM.seeAlso.name(), new StringBody(dataset.getMetadata().getSeeAlso(), utf8));
    entity.addPart(_WEBFORM.license.name(),
            new StringBody(dataset.getMetadata().getRights() == null ? ""
                    : (dataset.getMetadata().getRights().getURI() == null ? ""
                            : dataset.getMetadata().getRights().getURI()),
                    utf8));/*w w w  .  ja v a  2 s  .  c om*/
    entity.addPart(_WEBFORM.match.name(),
            new StringBody(dataset.getInputData().getImportMatchMode().name(), utf8));
    entity.addPart(_WEBFORM.file.name(), new FileBody(dataset.getInputData().getInputFile()));

    return entity;
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (mode != null) {
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        }/*  ww  w  .  j av  a 2s. com*/
        for (String key : parameters.keySet()) {
            List<Object> value = parameters.get(key);
            ContentType contentType = contentTypes.get(key);
            for (Object cur : value) {
                if (cur instanceof File) {
                    File file = (File) cur;
                    builder.addPart(key, new FileBody(file, contentType, file.getName()));
                } else if (cur instanceof InputStreamBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else if (cur instanceof ByteArrayBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else {
                    builder.addPart(key, new StringBody(cur.toString(), contentType));
                }
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

private static MultipartEntity getMultipartEntity(HttpServletRequest request) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Enumeration<String> en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String name = en.nextElement();
        String value = request.getParameter(name);
        try {/*w  ww .  j  a  v  a2s  . c om*/
            if (name.equals("file")) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(10000000);// 10 Mo
                List items = upload.parseRequest(request);
                Iterator itr = items.iterator();
                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(item.getName());
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(item.get());
                    fos.flush();
                    fos.close();
                    entity.addPart(name, new FileBody(file, "application/zip"));
                }
            } else {
                entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8")));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileUploadException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }

    return entity;

}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequestWithAddedServlet() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {//from  w  w w. java 2  s . c  o m
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/added";
        HttpPost post = new HttpPost(uri);
        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(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n"
                + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n"
                + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n"
                + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n",
                response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}