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:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception {
    Charset utf8 = Charset.forName("UTF-8");

    if ("text/uri-list".equals(attachment.getFormat())) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("title", attachment.getTitle()));
        formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription()));
        formparams.add(new BasicNameValuePair("folder",
                attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product"));
        return new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {//www. j  av a  2s  . c o m
        if (attachment.getResourceURL() == null)
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! ");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8);
        entity.addPart("title", new StringBody(attachment.getTitle(), utf8));
        entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8));
        entity.addPart("license", new StringBody("XMETDB", utf8));
        entity.addPart("file", new FileBody(new File(attachment.getResourceURL().toURI())));
        return entity;
    }
    //match, seeAlso, license
}

From source file:org.apache.hadoop.hdfs.qjournal.client.HttpImageUploadChannel.java

/**
 * Create a post request encapsulating bytes from the given
 * ByteArrayOutputStream./*from ww w .j ava  2  s .  co m*/
 */
private HttpPost setupRequest(ByteArrayOutputStream bos) {
    ContentBody cb = new ByteArrayBody(bos.toByteArray(), "image");
    HttpPost postRequest = new HttpPost(uri + "/uploadImage");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    // add a single part to the request
    reqEntity.addPart("file", cb);
    postRequest.setEntity(reqEntity);

    return postRequest;
}

From source file:org.exmaralda.webservices.BASChunkerConnector.java

public String callChunker(File bpfInFile, File audioFile, HashMap<String, Object> otherParameters)
        throws IOException, JDOMException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println("Chunker called at " + dateFormat.format(date)); //2016/11/16 12:08:43        System.out.println("Chunker called at " + Date.);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (otherParameters != null) {
        builder.addTextBody("language", (String) otherParameters.get("language"));
    }/*from w  w  w .  j a v a  2  s. c  om*/

    builder.addTextBody("aligner", "fast");
    builder.addTextBody("force", "rescue");
    builder.addTextBody("minanchorlength", "2");
    builder.addTextBody("boost_minanchorlength", "3");

    // add the text file
    builder.addBinaryBody("bpf", bpfInFile);

    // add the audio file
    builder.addBinaryBody("audio", audioFile);

    System.out.println("All parameters set. ");

    // construct a POST request with the multipart entity
    HttpPost httpPost = new HttpPost(chunkerURL);
    httpPost.setEntity(builder.build());

    System.out.println("URI: " + httpPost.getURI().toString());

    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity result = response.getEntity();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode == 200 && result != null) {
        String resultAsString = EntityUtils.toString(result);

        /*
        <WebServiceResponseLink>
            <success>true</success>
            <downloadLink>https://clarin.phonetik.uni-muenchen.de:443/BASWebServices/data/2019.01.03_15.58.41_9D4EECAD0791F9E9ED16DF35E66D1485/IDS_ISW_Chunker_Test_16kHz_OHNE_ANFANG.par</downloadLink>
            <output/>
            <warnings/>
        </WebServiceResponseLink>
        */

        // read the XML result string
        Document doc = FileIO.readDocumentFromString(resultAsString);

        // check if success == true
        Element successElement = (Element) XPath.selectSingleNode(doc, "//success");
        if (!((successElement != null) && successElement.getText().equals("true"))) {
            String errorText = "Call to BASChunker was not successful: "
                    + IOUtilities.elementToString(doc.getRootElement(), true);
            throw new IOException(errorText);
        }

        Element downloadLinkElement = (Element) XPath.selectSingleNode(doc, "//downloadLink");
        String downloadLink = downloadLinkElement.getText();

        // now we have the download link - just need to get the content as text
        String bpfOutString = downloadText(downloadLink);

        EntityUtils.consume(result);
        httpClient.close();

        return bpfOutString;
        //return resultAsString;
    } else {
        // something went wrong, throw an exception
        String reason = statusLine.getReasonPhrase();
        throw new IOException(reason);
    }

}

From source file:com.wishlist.Wishlist.java

public void uploadPhoto() {
    uploadCancelled = false;/*from ww w.j ava2  s. c o m*/
    dialog = ProgressDialog.show(Wishlist.this, "", getString(R.string.uploading_photo), true, true,
            new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    uploadCancelled = true;
                }
            });

    /*
     * Upload photo to the server in a new thread
     */
    new Thread() {
        public void run() {
            try {
                String postURL = HOST_SERVER_URL + HOST_PHOTO_UPLOAD_URI;

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(postURL);

                ByteArrayBody bab = new ByteArrayBody(imageBytes, "file_name_ignored");
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("source", bab);
                postRequest.setEntity(reqEntity);

                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();
                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                /*
                 * JSONObject is returned with image_name and image_url
                 */
                JSONObject jsonResponse = new JSONObject(s.toString());
                mProductImageName = jsonResponse.getString("image_name");
                mProductImageURL = jsonResponse.getString("image_url");
                dismissDialog();
                if (mProductImageName == null) {
                    showToast(getString(R.string.error_uploading_photo));
                    return;
                }
                /*
                 * photo upload finish, now publish to the timeline
                 */
                if (!uploadCancelled) {
                    mHandler.post(new Runnable() {
                        public void run() {
                            addToTimeline();
                        }
                    });
                }
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }
    }.start();
}

From source file:org.syncany.plugins.php.PhpTransferManager.java

@Override
public void upload(File localFile, RemoteFile remoteFile) throws StorageException {
    logger.info("Uploading: " + localFile.getName() + " to " + remoteFile.getName());
    try {/*  w  w w . j  av a  2s .  c om*/
        final String remote_name = remoteFile.getName();
        final File f = localFile;
        int r = operate("upload", new IPost() {
            List<NameValuePair> _nvps;

            public void mutateNVPS(List<NameValuePair> nvps) throws Exception {
                _nvps = nvps;
                nvps.add(new BasicNameValuePair("filename", remote_name));
            }

            public int mutatePost(HttpPost p) throws Exception {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.addPart("file", new FileBody(f));
                Iterator<NameValuePair> it = _nvps.iterator();
                while (it.hasNext()) {
                    NameValuePair nvp = it.next();
                    builder.addTextBody(nvp.getName(), nvp.getValue());
                }
                p.setEntity(builder.build());
                return -1;
            }

            @Override
            public int consumeResponse(InputStream s) throws Exception {
                String response = getAnswer(s);
                if (response.equals("true")) {
                    return 1;
                } else {
                    throw new Exception(response);
                }
            }

        });
        if (r != 1) {
            throw new Exception("Unexpected error, result code = " + r);
        }

    } catch (Exception e) {
        throw new StorageException("Cannot upload file " + remoteFile, e);
    }
}

From source file:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;//  w  ww .  j  a  va  2 s.com
    String hashPassword = md5Custom(password);
    JSONObject jsObj = new JSONObject();
    jsObj.put("group", group);
    jsObj.put("newHash", hashPassword);

    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.updateGroupAccess", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    }

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:ecblast.test.EcblastTest.java

public String compareReactions(String queryFormat, String query, String targetFormat, String target)
        throws Exception {
    DefaultHttpClient client;/*from   w ww  .jav a 2  s  .  c  om*/
    client = new DefaultHttpClient();
    String urlString = "http://localhost:8080/ecblast-rest/compare";
    HttpPost postRequest = new HttpPost(urlString);
    try {
        //Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : ""));
        //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));
        switch (queryFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(query));
            //Prepare payload
            multiPartEntity.addPart("q", fileBody);
            multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("q", new StringBody(query, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("Q", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }
        switch (targetFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(target));
            //Prepare payload
            multiPartEntity.addPart("t", fileBody);
            multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("t", new StringBody(target, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("T", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }

        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client.execute(postRequest);

        //Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());
            return response.toString();
        }
    } catch (IOException ex) {
    }
    return null;
}

From source file:com.google.cloud.solutions.smashpix.MainActivity.java

  /**
 * Uploads the image to Google Cloud Storage.
 *///from  w  ww  .  j av a2s  . c o  m
public Boolean uploadToCloudStorage(ServicesStorageSignedUrlResponse signedUrlParams,
  File localImageStoragePath){
  if (!signedUrlParams.isEmpty() && localImageStoragePath.exists())  {
    FileBody binary = new FileBody(localImageStoragePath);
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(signedUrlParams.getFormAction());
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      entity.addPart("bucket", new StringBody(signedUrlParams.getBucket()));
      entity.addPart("key", new StringBody(signedUrlParams.getFilename()));
      entity.addPart("policy", new StringBody(signedUrlParams.getPolicy()));
      entity.addPart("signature", new StringBody(signedUrlParams.getSignature()));
      entity.addPart("x-goog-meta-owner", new StringBody(accountName));
      entity.addPart("GoogleAccessId", new StringBody(signedUrlParams.getGoogleAccessId()));
      entity.addPart("file", binary);
    } catch (UnsupportedEncodingException e) {
      Log.e(Constants.APP_NAME, e.getMessage());
      return false;
    }

    httpPost.setEntity(entity);
    HttpResponse httpResponse;
    try {
      httpResponse = httpClient.execute(httpPost);
      if (httpResponse.getStatusLine().getStatusCode() == 204) {
        Log.i(Constants.APP_NAME, "Image Uploaded");
        return true;
      }
    } catch (ClientProtocolException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    } catch (IOException e) {
        Log.e(Constants.APP_NAME, e.getMessage());
    }
  }
  Log.e(Constants.APP_NAME, "Image Upload Failed");
  return false;
}

From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java

public void submitFile(String recordID, String fileField, BlobSubmissionType blob_value, CallingContext cc)
        throws MalformedURLException, IOException, EntityNotFoundException, ODKDatastoreException {

    String contentType = blob_value.getContentType(1, cc);
    String filename = blob_value.getUnrootedFilename(1, cc);
    filename = fileField + filename.substring(filename.lastIndexOf('.'));

    /**/*from   ww w  . java  2  s . com*/
     * REDCap server appears to be highly irregular in the structure of the
     * form-data submission it will accept from the client. The following should
     * work, but either resets the socket or returns a 403 error.
     */
    MultipartEntity postentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, UTF_CHARSET);
    FormBodyPart fb;
    fb = new FormBodyPart("token", new StringBody(getApiKey(), UTF_CHARSET));
    postentity.addPart(fb);
    fb = new FormBodyPart("content", new StringBody("file", UTF_CHARSET));
    postentity.addPart(fb);
    fb = new FormBodyPart("action", new StringBody("import", UTF_CHARSET));
    postentity.addPart(fb);
    fb = new FormBodyPart("record", new StringBody(recordID, UTF_CHARSET));
    postentity.addPart(fb);
    fb = new FormBodyPart("field", new StringBody(fileField, UTF_CHARSET));
    postentity.addPart(fb);
    fb = new FormBodyPart("file", new ByteArrayBody(blob_value.getBlob(1, cc), contentType, filename));
    postentity.addPart(fb);

    submitPost("File import", postentity, null, cc);
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

/**
 * Issue a POST against the API.//  www.  java  2  s  .c o m
 * 
 * @param path
 *            The web service endpoint
 * @param params
 *            A Map of key value pairs that are added to the post data
 * @param file
 *            The file to post
 * @param responseHandler
 *            The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response.
 * @return The response object from the operation. This response will be of
 *         the type given in the responseHandler argument.
 * @throws IOException
 *             If a network error occurs during the request.
 */
public <T> T doPost(String path, Map<String, String> params, File file, ResponseHandler<T> responseHandler)
        throws IOException {
    HttpPost post = new HttpPost();
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    multipartEntity.addPart(file.getName(), new FileBody(file));

    for (Map.Entry<String, String> paramEntry : params.entrySet()) {
        multipartEntity.addPart(new FormBodyPart(paramEntry.getKey(), new StringBody(paramEntry.getValue())));
    }

    post.setEntity(multipartEntity);

    return runMethod(post, path, responseHandler);
}