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.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox.//from   ww  w .ja v a 2 s . co  m
 */
public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException {
    String path = "/files/" + root + to_path;

    HttpClient client = getClient();

    try {
        String target = buildFullURL(secureProtocol, content_host, this.port,
                buildURL(path, API_VERSION, null));
        HttpPost req = new HttpPost(target);
        // 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<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("file", file_obj.getName()));
        req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        consumer.sign(req);

        // now we can add the real file multipart and we're good
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody bin = new FileBody(file_obj);
        entity.addPart("file", bin);
        // this resets it to the new entity with the real file
        req.setEntity(entity);

        HttpResponse resp = client.execute(req);

        resp.getEntity().consumeContent();
        return resp;
    } catch (Exception e) {
        throw new DropboxException(e);
    }
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

private static HttpEntity multipartEntity(String attachmentFileName, InputStream attachmentContent) {
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

    InputStreamBody inputStreamBody;//from   ww  w .  j  a v a  2  s .  co m
    if (isNotBlank(attachmentFileName)) {
        inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM, attachmentFileName);
    } else {
        inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM);
    }

    multipartEntityBuilder.addPart("file", inputStreamBody);

    return multipartEntityBuilder.build();
}

From source file:com.pc.dailymile.DailyMileClient.java

public Long addNoteWithImage(String note, File imageFile) throws Exception {
    HttpPost request = new HttpPost(DailyMileUtil.ENTRIES_URL);
    HttpResponse response = null;//from w  ww  .  ja v  a  2s.c  o m
    try {
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("media[data]", new FileBody(imageFile, "image/jpeg"));
        mpEntity.addPart("media[type]", new StringBody("image"));
        mpEntity.addPart("message", new StringBody(note));
        mpEntity.addPart("[share_on_services][facebook]", new StringBody("false"));
        mpEntity.addPart("[share_on_services][twitter]", new StringBody("false"));
        mpEntity.addPart("oauth_token", new StringBody(oauthToken));

        request.setEntity(mpEntity);
        // send the request
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            throw new RuntimeException(
                    "unable to execute POST - url: " + DailyMileUtil.ENTRIES_URL + " body: " + note);
        }

        if (statusCode == 201) {
            Header loc = response.getFirstHeader("Location");
            if (loc != null) {
                String locS = loc.getValue();
                if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) {
                    try {
                        return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1));
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
            }
        }

        return null;
    } finally {
        try {
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            }
            //EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.osbitools.ws.shared.web.BasicWebUtils.java

public WebResponse uploadFile(String path, String fname, InputStream in, String stoken)
        throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(path);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA);

    builder.addPart("fname", fn);
    builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname);

    BasicCookieStore cookieStore = new BasicCookieStore();

    if (stoken != null) {
        BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken);
        cookie.setDomain(TestConstants.JETTY_HOST);
        cookie.setPath("/");
        cookieStore.addCookie(cookie);//  w ww .  j av a  2s .  c o  m
    }

    TestConstants.LOG.debug("stoken=" + stoken);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    HttpEntity entity = builder.build();

    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    String body;
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        body = handler.handleResponse(response);
    } catch (HttpResponseException e) {
        return new WebResponse(e.getStatusCode(), e.getMessage());
    }

    return new WebResponse(response.getStatusLine().getStatusCode(), body);
}

From source file:cc.mincai.android.desecret.storage.dropbox.DropboxClient.java

/**
 * Put a file in the user's Dropbox./* w  ww. j  a v  a 2 s  . c  om*/
 */
@SuppressWarnings("unchecked")
public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException {
    String path = "/files/" + root + to_path;

    HttpClient client = getClient();

    try {
        String target = buildFullURL(secureProtocol, content_host, this.port,
                buildURL(path, API_VERSION, null));
        HttpPost req = new HttpPost(target);
        // 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 nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("file", file_obj.getName()));
        req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        auth.sign(req);

        // now we can add the real file multipart and we're good
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody bin = new FileBody(file_obj);
        entity.addPart("file", bin);
        // this resets it to the new entity with the real file
        req.setEntity(entity);

        HttpResponse resp = client.execute(req);

        resp.getEntity().consumeContent();
        return resp;
    } catch (Exception e) {
        throw new DropboxException(e);
    }
}

From source file:com.secdec.codedx.api.client.CodeDxClient.java

/**
 * Kicks off a CodeDx analysis run on a specified project
 *
 * @return A StartAnalysisResponse object
 * @param projectId The project ID//  w  w  w .  j ava2 s  .  co m
 * @param artifacts An array of streams to send over as analysis artifacts
 * @throws ClientProtocolException
 * @throws IOException
 * @throws CodeDxClientException
 *
 */
public StartAnalysisResponse startAnalysis(int projectId, InputStream[] artifacts)
        throws ClientProtocolException, IOException, CodeDxClientException {

    HttpPost postRequest = new HttpPost(url + "projects/" + projectId + "/analysis");
    postRequest.addHeader(KEY_HEADER, key);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (InputStream artifact : artifacts) {

        builder.addPart("file[]", new InputStreamBody(artifact, "file[]"));
    }

    HttpEntity entity = builder.build();

    postRequest.setEntity(entity);

    HttpResponse response = httpClient.execute(postRequest);

    int responseCode = response.getStatusLine().getStatusCode();

    if (responseCode != 202) {

        throw new CodeDxClientException(
                "Failed to start analysis.  " + IOUtils.toString(response.getEntity().getContent()),
                responseCode);
    }

    String data = IOUtils.toString(response.getEntity().getContent());

    return gson.<StartAnalysisResponse>fromJson(data, new TypeToken<StartAnalysisResponse>() {
    }.getType());
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

/**
 * Login to Bungeni via the OAuth route//www .  j  ava 2  s  . c o  m
 * @param oauthForwardURL
 * @param oauthCameFromURL
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
private String oauthAuthenticate(String oauthForwardURL, String oauthCameFromURL)
        throws UnsupportedEncodingException, IOException {

    final HttpPost post = new HttpPost(oauthForwardURL);
    final HashMap<String, ContentBody> nameValuePairs = new HashMap<String, ContentBody>();
    nameValuePairs.put("login", new StringBody(this.getUser()));
    nameValuePairs.put("password", new StringBody(this.getPassword()));
    nameValuePairs.put("camefrom", new StringBody(oauthCameFromURL));
    nameValuePairs.put("actions.login", new StringBody("login"));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }
    HttpContext context = new BasicHttpContext();
    post.setEntity(entity);
    HttpResponse oauthResponse = client.execute(post, context);
    // if the OAuth page retrieval failed throw an exception
    if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(oauthResponse.getStatusLine().toString());
    }
    String currentUrl = getRequestEndContextURL(context);
    // consume the response
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(oauthResponse);
    consumeContent(oauthResponse.getEntity());
    return currentUrl;
}

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

/**
 * attach log using run id/*from   www  .  j  a  v a 2s .c o m*/
 * 
 * @param token
 *            - token generate using username and password
 * @param scope
 *            : project:release:cycle
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) {
    try {
        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/testLog");

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

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate,
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId),
                        org.apache.http.entity.ContentType.TEXT_PLAIN);
                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:se.vgregion.service.barium.BariumRestClientImpl.java

/**
 * Do post multipart./*  w w  w.  ja va2  s  .  c om*/
 *
 * @param endpoint    the endpoint
 * @param fileName    the file name
 * @param inputStream the input stream
 * @return the string
 * @throws BariumException the barium exception
 */
String doPostMultipart(String endpoint, String fileName, InputStream inputStream) throws BariumException {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("140.166.209.205", 8888));

    HttpPost httpPost = new HttpPost(this.apiLocation + endpoint);

    if (ticket != null) {
        httpPost.setHeader("ticket", ticket);
    } else {
        this.connect();
        httpPost.setHeader("ticket", ticket);
    }

    try {
        ContentBody contentBody = new InputStreamBody(inputStream, fileName);

        // Must use HttpMultipartMode.BROWSER_COMPATIBLE in order to use UTF-8 instead of US_ASCII to handle special
        // characters.
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName("UTF-8")) {

            // Due to a bug in Barium we must not append the charset directive to the content-type header since
            // nothing is created in Barium if doing so.
            // todo Try skipping this when we use Barium Live?
            @Override
            protected String generateContentType(final String boundary, final Charset charset) {
                StringBuilder buffer = new StringBuilder();
                buffer.append("multipart/form-data; boundary=");
                buffer.append(boundary);
                // Comment out this
                /*if (charset != null) {
                buffer.append("; charset=");
                buffer.append(charset.name());
                }*/
                return buffer.toString();
            }
        };

        multipartEntity.addPart("Data", contentBody);

        httpPost.setEntity(multipartEntity);

        HttpResponse response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new BariumException(
                    "Failed to post multipart. Reason: " + response.getStatusLine().getReasonPhrase());
        }

        InputStream content = response.getEntity().getContent();

        return toString(content);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}