Example usage for org.apache.http.entity.mime MultipartEntityBuilder create

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:com.game.simple.Game3.java

public static void uploadAvatar(final String token) {
    //---timer---//
    //StartReConnect();
    //-----------//
    self.runOnUiThread(new Runnable() {
        public void run() {
            if (cropedImagePath == null) {
                Toast.makeText(self.getApplicationContext(), "Cha chn nh !",
                        Toast.LENGTH_SHORT).show();
                return;
            }//from w  w w.  j ava  2 s  . c  o m
            if (cropedImagePath.compareTo(" ") == 0) {

                Toast.makeText(self.getApplicationContext(), "Cha chn nh !",
                        Toast.LENGTH_SHORT).show();
                return;
            } else {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPostRequest = new HttpPost(url);
                try {

                    File file = new File(cropedImagePath);
                    FileBody bin = new FileBody(file);
                    StringBody tok = new StringBody(token);
                    StringBody imageType = new StringBody("jpg");
                    MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
                    multiPartEntityBuilder.addPart("token", tok);
                    multiPartEntityBuilder.addPart("imageType", imageType);
                    multiPartEntityBuilder.addPart("media", bin);
                    httpPostRequest.setEntity(multiPartEntityBuilder.build());

                    // Execute POST request to the given URL
                    HttpResponse httpResponse = null;
                    httpResponse = httpClient.execute(httpPostRequest);
                    // receive response as inputStream
                    InputStream inputStream = null;
                    inputStream = httpResponse.getEntity().getContent();

                    Log.e("--upload", "Upload complete");
                    Toast.makeText(self.getApplicationContext(), "Upload thnh cng!", Toast.LENGTH_SHORT)
                            .show();
                    String result = "";
                    if (inputStream != null)
                        result = convertInputStreamToString(inputStream);
                    else
                        result = " ";

                    Log.e("upload", result);
                    setlinkAvata(result);
                    cropedImagePath = " ";

                } catch (Exception e) {

                    Log.e("--Upload--", "ko the upload ");
                    Toast.makeText(self.getApplicationContext(),
                            "C li trong qu trnh upload!", Toast.LENGTH_SHORT).show();
                }
            } //else
        }
    });
    //---timer---//
    stopTimer();
    //-----------//
}

From source file:UploadTest.java

@Test
public void appache_test() throws ClientProtocolException, IOException {

    String user = "edoweb-admin";
    String password = "admin";
    String encoding = Base64.encodeBase64String((user + ":" + password).getBytes());
    System.out.println(encoding);
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    URL myurl = new URL("http://localhost:9000/resource/frl:6376984/data");

    // ----------------------------------------------------------------------------

    String boundary = "==" + System.currentTimeMillis() + "===";
    String filePath = "/home/raul/test/frl%3A6376982/123.txt";
    File file = new File(filePath);
    String fileLength = Long.toString(file.getTotalSpace());
    HttpEntity entity = MultipartEntityBuilder.create().addTextBody("data", boundary)
            .addBinaryBody("data", file, ContentType.create("application/pdf"), "6376986.pdf").build();
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    HttpPut put = new HttpPut(myurl.toString());
    // put.setHeader("Authorization", "Basic " + encoding);
    // put.setHeader("Accept", "*/*");
    // put.setHeader("Content-Length", fileLength);
    put.setEntity(entity);//www  .  ja  v a2s .  co  m
    HttpResponse response = client.execute(put);
    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println(statusCode);
    Assert.assertEquals(statusCode, HttpStatus.SC_OK);
}

From source file:io.swagger.client.api.CameraApi.java

/**
* Stop recording a movie/*from ww w .j  a v a  2s . c om*/
* 
 * @return void
*/
public void captureStopPost() throws TimeoutException, ExecutionException, InterruptedException, ApiException {
    Object postBody = null;

    // create path and map variables
    String path = "/capture/stop".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody,
                headerParams, formParams, contentType, authNames);
        if (localVarResponse != null) {
            return;
        } else {
            return;
        }
    } catch (ApiException ex) {
        throw ex;
    } catch (InterruptedException ex) {
        throw ex;
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof VolleyError) {
            VolleyError volleyError = (VolleyError) ex.getCause();
            if (volleyError.networkResponse != null) {
                throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
            }
        }
        throw ex;
    } catch (TimeoutException ex) {
        throw ex;
    }
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry7.QMetryRestWebservice.java

public int attachTestLogs(long tcVersionIdASEntityId, File filePath) {
    try {/*from  w w w . java 2s .  c o  m*/
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments");

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

                FileBody bin = new FileBody(filePath);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:org.dawnsci.marketplace.ui.editors.OverviewPage.java

protected void uploadFile(CloseableHttpClient client, Path path, String segment)
        throws ClientProtocolException, IOException {
    String token = getCsrfToken(client);
    String url = getMarketplaceUrl();

    // upload the p2-repository file
    HttpPost httpPost = new HttpPost(url + "/" + segment);
    httpPost.addHeader(X_CSRF_TOKEN, token);
    HttpEntity file = MultipartEntityBuilder.create().addBinaryBody("file", path.toFile())
            .addTextBody("id", solution.getId().toString()).build();
    httpPost.setEntity(file);//from   w w w .  ja  v  a  2s  . com
    HttpResponse response = client.execute(httpPost);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        String result = EntityUtils.toString(response.getEntity());
        // obtain some key values from the server version
        // and update the local instance
        Node node = MarketplaceSerializer.deSerializeSolution(result);
        solution.setChanged(node.getChanged());
        addMessage(IMessage.INFORMATION, "File " + path.getFileName() + " uploaded");
    } else {
        String reasonPhrase = response.getStatusLine().getReasonPhrase();
        addMessage(IMessage.ERROR, reasonPhrase);
    }
}

From source file:org.apache.sling.testing.clients.SlingClient.java

/**
 * Uploads a file to the repository. It creates a leaf node typed {@code nt:file}. The intermediary nodes are created with
 * type "sling:OrderedFolder" if parameter {@code createFolders} is true
 *
 * @param file           the file to be uploaded
 * @param mimeType       the MIME Type of the file
 * @param toPath         the complete path of the file in the repository including file name
 * @param createFolders  if true, all non existing parent nodes will be created using node type {@code sling:OrderedFolder}
 * @param expectedStatus list of expected HTTP Status to be returned, if not set, 201 is assumed.
 * @return               the response//  www  .ja  v  a  2s  .c  o m
 * @throws ClientException if something fails during the request/response cycle
 */
public SlingHttpResponse upload(File file, String mimeType, String toPath, boolean createFolders,
        int... expectedStatus) throws ClientException {
    // Determine filename and parent folder, depending on whether toPath is a folder or a file
    String toFileName;
    String toFolder;
    if (toPath.endsWith("/")) {
        toFileName = file.getName();
        toFolder = toPath;
    } else {
        toFileName = getNodeNameFromPath(toPath);
        toFolder = getParentPath(toPath);
    }

    if (createFolders) {
        createNodeRecursive(toFolder, "sling:OrderedFolder");
    }

    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }

    HttpEntity entity = MultipartEntityBuilder.create()
            .addBinaryBody(toFileName, file, ContentType.create(mimeType), toFileName).build();

    // return the sling response
    return this.doPost(toFolder, entity, HttpUtils.getExpectedStatus(SC_CREATED, expectedStatus));
}

From source file:utils.APIImporter.java

/**
 * update the content of a document of the API been sent
 * @param folderPath folder path to the imported API
 * @param uuid uuid of the API//from   w w  w .j a v  a 2 s . c  om
 * @param response payload for the publishing document
 * @param accessToken access token
 */
private static void addDocumentContent(String folderPath, String uuid, String response, String accessToken) {
    String documentId = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_ID);
    String sourceType = ImportExportUtils.readJsonValues(response, ImportExportConstants.SOURCE_TYPE);
    String documentName = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
    String directoryName;
    //setting directory name depending on the document source type
    if (sourceType.equals(ImportExportConstants.INLINE_DOC_TYPE)) {
        directoryName = ImportExportConstants.INLINE_DOCUMENT_DIRECTORY;
    } else {
        directoryName = ImportExportConstants.FILE_DOCUMENT_DIRECTORY;
    }
    //getting document content
    String documentContentPath = folderPath + ImportExportConstants.DIRECTORY_SEPARATOR
            + ImportExportConstants.DOCUMENT_DIRECTORY + ImportExportConstants.DIRECTORY_SEPARATOR
            + directoryName + ImportExportConstants.DIRECTORY_SEPARATOR + documentName;
    File content = new File(documentContentPath);
    HttpEntity entity = null;
    if (sourceType.equals(ImportExportConstants.FILE_DOC_TYPE)) {
        //adding file type content
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, content);
        entity = multipartEntityBuilder.build();
    } else {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(content));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            String inlineContent = sb.toString();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addTextBody(ImportExportConstants.MULTIPART_Inline, inlineContent,
                    ContentType.APPLICATION_OCTET_STREAM);
            entity = multipartEntityBuilder.build();
        } catch (IOException e) {
            errorMsg = "error occurred while retrieving content of document "
                    + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
            log.error(errorMsg, e);
        } finally {
            IOUtils.closeQuietly(br);
        }
    }
    String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId + "/content";
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    HttpPost request = new HttpPost(url);
    request.setHeader(HttpHeaders.AUTHORIZATION,
            ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
    request.setEntity(entity);
    try {
        client.execute(request);
    } catch (IOException e) {
        errorMsg = "error occurred while uploading the content of document "
                + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME);
        log.error(errorMsg, e);
    }
}

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Uploads the file and finalizes the printing
 *
 * @param printJob    {PrintJob} - the print job
 * @param prevElement {Element} - the previous Jsoup element containing the
 *                    upload file Html/*from  w w  w  .j  a v  a 2 s  . co  m*/
 *
 * @return {boolean} - whether or not the print job completed
 */
static boolean uploadFile(PrintJob printJob, Document prevElement)
        throws PrintingException, UnsupportedMimeTypeException {
    String uploadUrl = printJob.getSession().getDomain().replace("/app", "")
            + PrintApi.getUploadFileUrl(prevElement); // upload directory

    HttpPost post = new HttpPost(uploadUrl);
    CloseableHttpClient client = HttpClientBuilder.create().build();

    // configure multipart post request entity builder
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    // build the file boundary
    String boundary = "-----------------------------" + new Date().getTime();
    entityBuilder.setBoundary(boundary);

    // set the file
    File file = new File(printJob.getFilePath());
    FileBody body = new FileBody(file,
            ContentType.create(ContentTypes.getApplicationType(printJob.getFilePath())), file.getName());
    entityBuilder.addPart("file[]", body);

    // build the post request
    HttpEntity multipart = entityBuilder.build();
    post.setEntity(multipart);

    // set cookie
    post.setHeader("Cookie", printJob.getSession().getSessionKey() + "=" + printJob.getSession().getSession());

    // send
    try {
        CloseableHttpResponse response = client.execute(post);
        return response.getStatusLine().getStatusCode() == 200;
    } catch (IOException e) {
        throw new PrintingException("Error uploading the file");
    }
}