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:fi.hut.soberit.sensors.services.BatchDataUploadService.java

private boolean uploadFile(final HttpClient client, File file)
        throws IOException, ClientProtocolException, JSONException, UnsupportedEncodingException {
    Log.d(TAG, "uploadFile " + file);

    final HttpPost httpost = new HttpPost(apiUri);

    final MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    populateMultipartEntity(multipartEntity, file);

    httpost.setEntity(multipartEntity);/*from w w w. j  av a  2s  .  co  m*/

    final HttpResponse fileUploadResponse = client.execute(httpost);
    final String uploadResult = getRequestContent(fileUploadResponse);

    if (uploadResult == null) {

        showBatchUploadNotification(getString(R.string.batch_upload_failed), 75, false);
        return false;
    }

    final JSONObject root = (JSONObject) new JSONTokener(uploadResult).nextValue();

    if (root.has(UPLOAD_RESULT_MESSAGE)) {
        final String message = root.getInt(UPLOAD_RESULT_CODE) == 200
                ? getString(R.string.batch_upload_successful)
                : getString(R.string.batch_upload_failed);

        showBatchUploadNotification(message, MAX_PROGRESS, false);

        return true;
    }

    return false;
}

From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java

@Override
public Promise<Void> addAttachment(final URI attachmentsUri, final InputStream inputStream,
        final String filename) {
    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.defaultCharset());
    entity.addPart(FILE_BODY_TYPE, new InputStreamBody(inputStream, filename));
    return postAttachments(attachmentsUri, entity);
}

From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java

@Override
public Promise<Void> addAttachments(final URI attachmentsUri, final AttachmentInput... attachments) {
    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.defaultCharset());
    for (final AttachmentInput attachmentInput : attachments) {
        entity.addPart(FILE_BODY_TYPE,// ww  w . j a  va 2s.  c  om
                new InputStreamBody(attachmentInput.getInputStream(), attachmentInput.getFilename()));
    }
    return postAttachments(attachmentsUri, entity);
}

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

/**
 * attach log using run id/*from   w w  w. jav a2  s .com*/
 * 
 * @param token
 *            - token generate using username and password
 * @param projectID
 * @param releaseID
 * @param cycleID
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID,
        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(baseURL + "/rest/attachments/testLog");

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

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID);

                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:com.licryle.httpposter.HttpPoster.java

/**
 * Builds the {@link _ProgressiveEntity} that we will send to the server.
 * Takes for input an {@link HttpConfiguration} that contains the Post
 * variables and File Names to send./*  w  w  w  .j av  a2  s .c  om*/
 *
 * @param mConf Configuration of the POST request to be processed.
 * @return A ProgressiveEntity which progress can be tracked as we send it to
 * the server.
 *
 * @throws IOException When a file in the list of files from
 * {@link HttpConfiguration#getFiles()} cannot be read.
 *
 * @see {@link com.licryle.httpposter.HttpPoster._ProgressiveEntity}
 * @see {@link com.licryle.httpposter.HttpConfiguration}
 */
protected _ProgressiveEntity _buildEntity(HttpConfiguration mConf) throws IOException {
    Log.d("HttpPoster", String.format("_buildEntity: Entering for Instance %d", _iInstanceId));

    /********* Build request content *********/
    MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setBoundary(mConf.getHTTPBoundary());

    int iFileNb = 0;
    Iterator mFiles = mConf.getFiles().iterator();
    while (mFiles.hasNext()) {
        final File mFile = (File) mFiles.next();

        try {
            mBuilder.addBinaryBody("file_" + iFileNb, mFile, ContentType.DEFAULT_BINARY, mFile.getName());
        } catch (Exception e) {
            throw new IOException();
        }

        iFileNb++;
    }

    Iterator mArgs = mConf.getArgs().entrySet().iterator();
    while (mArgs.hasNext()) {
        Map.Entry mPair = (Map.Entry) mArgs.next();

        mBuilder.addTextBody((String) mPair.getKey(), (String) mPair.getValue(),
                ContentType.MULTIPART_FORM_DATA);
    }

    Log.d("HttpPoster", String.format("_buildEntity: Leaving for Instance %d", _iInstanceId));

    return new _ProgressiveEntity(mBuilder.build(), this);
}

From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws IOException, UnsupportedOperationException {
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding/*from w ww  .j a v  a2  s  .c  o  m*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public int post(String url, Map<String, Object> data, PostType dataType, String charset, String referrer) {
    clearPreviousRequest();/*from   www. j  a v  a 2 s  .c o  m*/

    HttpPost request = new HttpPost(url);
    HttpEntity entity = null;

    if (charset == null) {
        charset = "utf-8";
    }

    Charset detectedCharset = null;
    try {
        detectedCharset = Charset.forName(charset);
    } catch (Exception ex) {
        LOG.warn("invalid charset name {}, switching to utf-8");
        detectedCharset = Charset.forName("utf-8");
    }

    data = handleUnsupportedEncoding(data, detectedCharset);

    switch (dataType) {
    case URL_ENCODED:
        List<NameValuePair> formparams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String) {
                formparams.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
            } else {
                LOG.warn("trying to url encode non string data");
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        try {
            entity = new UrlEncodedFormEntity(formparams, detectedCharset);
        } catch (Exception ex) {
            statusCode = -1;
            exception = ex;
            return statusCode;
        }
        break;

    case MULTIPART:
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(detectedCharset)
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        ContentType formDataCT = ContentType.create("form-data", detectedCharset);
        //                formDataCT = ContentType.DEFAULT_TEXT;

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue() instanceof String) {
                builder = builder.addTextBody(key, (String) entry.getValue(), formDataCT);
            } else if (entry.getValue() instanceof byte[]) {
                builder = builder.addBinaryBody(key, (byte[]) entry.getValue());
            } else if (entry.getValue() instanceof ContentBody) {
                builder = builder.addPart(key, (ContentBody) entry.getValue());
            } else {
                exception = new UnsupportedOperationException(
                        "unssuported body type " + entry.getValue().getClass());
                return statusCode = -1;
            }
        }

        entity = builder.build();
        break;

    default:
        exception = new UnsupportedOperationException("unspported PostType " + dataType);
        return statusCode = -1;
    }

    request.setEntity(entity);
    if (referrer != null) {
        request.addHeader("Referer", referrer);
    }
    return request(request);
}

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

public String callG2P(File bpfInFile, HashMap<String, Object> otherParameters)
        throws IOException, JDOMException {

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

    if (otherParameters != null) {
        builder.addTextBody("lng", (String) otherParameters.get("lng"));
    }/*from  w ww  .j ava2s  .c  om*/

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

    // construct a POST request with the multipart entity
    HttpPost httpPost = new HttpPost(g2pURL);
    httpPost.setEntity(builder.build());
    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);
        BASWebServiceResult basResult = new BASWebServiceResult(resultAsString);
        if (!(basResult.isSuccess())) {
            String errorText = "Call to G2P was not successful: " + resultAsString;
            throw new IOException(errorText);
        }
        String bpfOutString = basResult.getDownloadText();

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

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

From source file:com.k42b3.neodym.oauth.Oauth.java

@SuppressWarnings("unused")
private HttpEntity httpRequest(String method, String url, Map<String, String> header, String body)
        throws Exception {
    // build request
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpRequestBase request;// ww  w .jav  a2  s  .c  o  m

    if (method.equals("GET")) {
        request = new HttpGet(url);
    } else if (method.equals("POST")) {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("text", new StringBody(body));

        request = new HttpPost(url);

        ((HttpPost) request).setEntity(entity);
    } else {
        throw new Exception("Invalid request method");
    }

    // header
    Set<String> keys = header.keySet();

    for (String key : keys) {
        request.setHeader(key, header.get(key));
    }

    // execute HTTP Get Request
    logger.info("Request: " + request.getRequestLine());

    HttpResponse httpResponse = httpClient.execute(request);

    HttpEntity entity = httpResponse.getEntity();

    String responseContent = EntityUtils.toString(entity);

    // log traffic
    if (trafficListener != null) {
        TrafficItem trafficItem = new TrafficItem();

        trafficItem.setRequest(request);
        trafficItem.setResponse(httpResponse);
        trafficItem.setResponseContent(responseContent);

        trafficListener.handleRequest(trafficItem);
    }

    // check status code
    int statusCode = httpResponse.getStatusLine().getStatusCode();

    if (!(statusCode >= 200 && statusCode < 300)) {
        JOptionPane.showMessageDialog(null, responseContent);

        throw new Exception("No successful status code");
    }

    return entity;
}

From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java

@Override
public Promise<Void> addAttachments(final URI attachmentsUri, final File... files) {
    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.defaultCharset());
    for (final File file : files) {
        entity.addPart(FILE_BODY_TYPE, new FileBody(file));
    }//from w  w w . j a  v  a  2 s . c  o  m
    return postAttachments(attachmentsUri, entity);
}