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:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUploadWithEagerParsing() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {//  w  w  w.j a v  a2s .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:ecblast.test.EcblastTest.java

public String atomAtomMappingSMI(String query, String type)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(MultiPartWriter.class);
    Client client = Client.create(cc);/*from ww  w.j a v a 2s .  c o  m*/
    String urlString = "http://localhost:8080/ecblast-rest/aam";
    WebResource webResource = client.resource("http://localhost:8080/ecblast-rest/aam");
    //String smi = "[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12])[CH3:6].[H:30][OH:14]>>[H:30][O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12].[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([OH:14])[CH3:6]";

    FormDataMultiPart form = new FormDataMultiPart();
    switch (type) {
    case "SMI":
        form.field("q", query);
        form.field("Q", "SMI");
        break;
    case "RXN":
        /*MultivaluedMapImpl values = new MultivaluedMapImpl();
        values.add("q", new File(query));
        values.add("Q", "RXN");
        ClientResponse response = webResource.type(MediaType.).post(ClientResponse.class, values);
        return response.toString();
                
        File attachment = new File(query);
                
        FileInputStream fis = null;
                
        fis = new FileInputStream(attachment);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
        bos.write(buf, 0, readNum); //no doubt here is 0
        }
        fis.close();
        bos.close();
        } catch (IOException ex) {
        try {
        fis.close();
        bos.close();
        } catch (IOException e) {
        return "ERROR";
        }
        return "ERROR";
                
        }
        byte[] bytes = bos.toByteArray();
                
        FormDataBodyPart bodyPart = new FormDataBodyPart("q", new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM_TYPE);
        form.bodyPart(bodyPart);
        //form.field("q", bodyPart);
        //form.field*
        form.field("Q", "RXN", MediaType.MULTIPART_FORM_DATA_TYPE);*/
        DefaultHttpClient client1;
        client1 = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(urlString);
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        // FileBody queryFileBody = new FileBody(queryFile);
        multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : ""));
        //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));
        File file = new File(query);
        FileBody fileBody = new FileBody(file);
        //Prepare payload
        multiPartEntity.addPart("q", fileBody);
        multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client1.execute(postRequest);
        return response.toString();
    }
    form.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

    ClientResponse responseJson = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class,
            form);
    return responseJson.toString();
}

From source file:com.ad.mediasharing.ADUploadMediaTask.java

@Override
protected String doInBackground(Void... params) {

    String serverResponse = "";

    try {//  w ww. ja  v  a2s.c  o m

        // Set timeout parameters
        int timeout = ADMediaSharingConstants.UPLOAD_REQUEST_TIME_OUT;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
        HttpConnectionParams.setSoTimeout(httpParameters, timeout);

        // Initiate connection parts
        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpPost postRequest = new HttpPost(mRequest.getRemoteRequestUri());

        // Add headers
        if (!mRequest.getRequestHeaders().isEmpty()) {
            for (String sKey : mRequest.getRequestHeaders().keySet()) {

                String sValue = mRequest.getRequestHeaders().get(sKey);
                postRequest.addHeader(sKey, sValue);
            }
        }

        FileBody media = getMediaType(mRequest.getMediaFile());
        postRequest.addHeader("Media-Type", media.getMimeType());

        ADCustomMultiPartEntity multipartE = new ADCustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new ADCustomMultiPartEntity.ProgressListener() {

                    int lastPourcent = 0;

                    @TargetApi(Build.VERSION_CODES.CUPCAKE)
                    @Override
                    public void transferred(long num) {
                        int currentPourcent = (int) ((num / (float) totalSize) * 100);
                        if (currentPourcent > lastPourcent && currentPourcent < 90) {
                            publishProgress(currentPourcent);
                            lastPourcent = currentPourcent;
                        }
                    }
                });

        // Add the post elements
        multipartE.addPart("file", media);
        if (mRequest.getPostBodyParams() != null) {
            for (String sKey : mRequest.getPostBodyParams().keySet()) {
                String sVal = mRequest.getPostBodyParams().get(sKey);

                multipartE.addPart(sKey, new StringBody(sVal));
            }
        }

        totalSize = multipartE.getContentLength();
        postRequest.setEntity(multipartE);

        HttpResponse response = client.execute(postRequest);

        // Get the response from server
        HttpEntity theEnt = response.getEntity();
        serverResponse = EntityUtils.toString(theEnt);

        if (ADMediaSharingConstants.DEBUG) {
            Log.d(TAG, "Result: " + serverResponse);
        }

        //Show the remaining progress.
        mProgressHandler.post(new Runnable() {
            public void run() {
                int i = uploadProgress;
                while (i <= 100) {
                    try {
                        publishProgress(i);
                        i++;
                    } catch (Exception e) {
                        if (ADMediaSharingConstants.DEBUG)
                            Log.d(TAG, e.getMessage());
                    }
                }
            }
        });
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        serverResponse = "unreachable";
    } catch (ConnectTimeoutException e) {
        e.printStackTrace();
        serverResponse = "unreachable";
    } catch (Exception e) {
        e.printStackTrace();
        serverResponse = "unreachable";
    }

    return serverResponse;
}

From source file:com.box.androidlib.FileTransfer.BoxFileUpload.java

/**
 * Execute a file upload./*from  www. java2 s  . c o  m*/
 * 
 * @param action
 *            Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}
 * @param file
 *            A File resource pointing to the file you wish to upload. Make sure File.isFile() and File.canRead() are true for this resource.
 * @param filename
 *            The desired filename on Box after upload (just the file name, do not include the path)
 * @param destinationId
 *            If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that
 *            is being overwritten, or copied.
 * @return A FileResponseParser with information about the upload.
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 * @throws FileNotFoundException
 *             File being uploaded either doesn't exist, is not a file, or cannot be read
 * @throws MalformedURLException
 *             Make sure you have specified a valid upload action
 */
public FileResponseParser execute(final String action, final File file, final String filename,
        final long destinationId) throws IOException, MalformedURLException, FileNotFoundException {
    if (!file.isFile() || !file.canRead()) {
        throw new FileNotFoundException("Specified upload file is either not a file, or cannot be read");
    }

    if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE)
            && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        throw new MalformedURLException("action must be upload, overwrite or new_copy");
    }

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getUploadUrlScheme());
    builder.authority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    builder.appendQueryParameter("file_name", filename);

    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE);
    if (mListener != null && mHandler != null) {
        reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() {

            @Override
            public void onTransferred(final long bytesTransferredCumulative) {
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListener.onProgress(bytesTransferredCumulative);
                    }
                });
            }
        });
    }

    reqEntity.addPart(filename, new FileBody(file) {

        @Override
        public String getFilename() {
            return filename;
        }
    });
    post.setEntity(reqEntity);

    // Send request
    final HttpResponse httpResponse;
    try {
        httpResponse = (new DefaultHttpClient()).execute(post);
    } catch (final IOException e) {
        // Detect if the download was cancelled through thread interrupt.
        // See CountingOutputStream.write() for when this exception is thrown.
        if (e.getMessage().equals(FileUploadListener.STATUS_CANCELLED)) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    }

    String status = null;
    BoxFile boxFile = null;
    final InputStream is = httpResponse.getEntity().getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    httpResponse.getEntity().consumeContent();
    final String xml = sb.toString();

    try {
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));
        final Node statusNode = doc.getElementsByTagName("status").item(0);
        if (statusNode != null) {
            status = statusNode.getFirstChild().getNodeValue();
        }
        final Element fileEl = (Element) doc.getElementsByTagName("file").item(0);
        if (fileEl != null) {
            try {
                boxFile = Box.getBoxFileClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fileEl.getAttributes().getLength(); i++) {
                boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(),
                        fileEl.getAttributes().item(i).getNodeValue());
            }
        }

        // errors are NOT returned as properly formatted XML yet so in this
        // case the raw response is the error status code
        // see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        if (status == null) {
            status = xml;
        }
    } catch (final SAXException e) {
        // errors are NOT returned as properly formatted XML yet so in this
        // case the raw response is the error status code
        // see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        status = xml;
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    }
    final FileResponseParser handler = new FileResponseParser();
    handler.setFile(boxFile);
    handler.setStatus(status);
    return handler;
}

From source file:ninja.utils.NinjaTestBrowser.java

public String uploadFile(String url, String paramName, File fileToUpload) {

    String response = null;// w w w. j  a  v a 2 s  .  c  o  m

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost post = new HttpPost(url);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        entity.addPart(paramName, new FileBody((File) fileToUpload));

        post.setEntity(entity);

        // Here we go!
        response = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        post.releaseConnection();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return response;

}

From source file:com.jelastic.JelasticService.java

public UploadResponse upload(AuthenticationResponse authenticationResponse) {
    UploadResponse uploadResponse = null;
    try {//  w w  w . ja  va  2  s . com
        DefaultHttpClient httpclient = getHttpClient();

        final File file = new File(getDir() + File.separator + getFilename());
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "First build artifact and try again. Artifact not found in location: ["
                            + file.getAbsolutePath() + "]");
        }

        CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new CustomMultiPartEntity.ProgressListener() {
                    public void transferred(long num) {
                        if (((int) ((num / (float) totalSize) * 100)) != numSt) {
                            System.out.println(
                                    "File Uploading : [" + (int) ((num / (float) totalSize) * 100) + "%]");
                            numSt = ((int) ((num / (float) totalSize) * 100));
                        }
                    }
                });

        multipartEntity.addPart("fid", new StringBody("123456"));
        multipartEntity.addPart("session", new StringBody(authenticationResponse.getSession()));
        multipartEntity.addPart("file", new FileBody(file));
        totalSize = multipartEntity.getContentLength();

        URI uri = URIUtils.createURI(getProtocol(), getApiHoster(), getPort(), getUrlUploader(), null, null);
        project.log("Upload url : " + uri.toString(), Project.MSG_DEBUG);
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(multipartEntity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpPost, responseHandler);
        project.log("Upload response : " + responseBody, Project.MSG_DEBUG);

        uploadResponse = deserialize(responseBody, UploadResponse.class);
    } catch (URISyntaxException | IOException e) {
        project.log(e.getMessage(), Project.MSG_ERR);
    }
    return uploadResponse;
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageUpload.java

static HttpPost createRequest(String httpAddress, ContentBody cb) {
    HttpPost postRequest = new HttpPost(httpAddress + "/uploadImage");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("file", cb);
    postRequest.setEntity(reqEntity);/*  w w  w.  j a v a2 s  .c  o m*/
    return postRequest;
}

From source file:com.nc.common.utils.HttpUtils.java

/**
 * <pre>//from w ww  .j a va 2 s .co  m
 * 1.  : http  
 * 2.  : OpenAPI Multipart 
 * </pre>
 *
 * @method Name : execOpenAPIMultipart
 * @param String subUrl, Map<String, Object> paramMap
 * @return String
 * @throws Exception
 * 
 */
public String execOpenAPIMultipart(String subUrl, Map<String, Object> paramMap) throws Exception {
    String result = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        HttpPost httpPost = new HttpPost(new URI(serverOpenAPI + subUrl));
        // httpPost.addHeader("Content-Type", "application/json");

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .setCharset(Charset.forName(CommonConstants.DEFAULT_CHARSET));

        Iterator<String> iter = paramMap.keySet().iterator();
        String key = null;
        String val = null;

        while (iter.hasNext()) {
            key = iter.next();
            val = (String) paramMap.get(key);

            if (log.isDebugEnabled()) {
                log.debug(
                        "==========================================================================================");
                log.debug(" = ? : [{} - {}] =", key, val);
                log.debug(
                        "==========================================================================================");
            }

            multipartEntityBuilder.addTextBody(key, val);
        }
        httpPost.setEntity(multipartEntityBuilder.build());

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API   : [{}]", httpPost);
            log.debug(
                    "==========================================================================================");
        }

        CloseableHttpResponse response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API  ? : [{}]", statusLine);
            log.debug(
                    "==========================================================================================");
        }

        try {
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, CommonConstants.DEFAULT_CHARSET);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "==========================================================================================");
                        log.debug("= API    : [{}] =", result);
                        log.debug(
                                "==========================================================================================");
                    }
                }
                EntityUtils.consume(entity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:cn.dacas.emmclient.security.ssl.SslHttpStack.java

/**
 * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
 * @param httpRequest/*  w w w.  ja  v  a  2 s. c o m*/
 * @param request
 * @throws AuthFailureError
 */
private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {

    // Return if Request is not MultiPartRequest
    if (request instanceof MultiPartRequest == false) {
        return;
    }

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    //Iterate the fileUploads
    Map<String, File> fileUpload = ((MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        multipartEntity.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }

    //Iterate the stringUploads
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        try {
            multipartEntity.addPart(((String) entry.getKey()), new StringBody((String) entry.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    httpRequest.setEntity(multipartEntity);
}