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.olat.test.rest.RepositoryRestClient.java

public CourseVO deployCourse(File archive, String resourcename, String displayname)
        throws URISyntaxException, IOException {

    RestConnection conn = new RestConnection(deploymentUrl);
    assertTrue(conn.login(username, password));

    URI request = UriBuilder.fromUri(deploymentUrl.toURI()).path("restapi").path("repo/courses").build();
    HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON);
    String softKey = UUID.randomUUID().toString();
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", archive, ContentType.APPLICATION_OCTET_STREAM, archive.getName())
            .addTextBody("filename", archive.getName()).addTextBody("resourcename", resourcename)
            .addTextBody("displayname", displayname).addTextBody("access", "3").addTextBody("softkey", softKey)
            .build();/* w ww  .j  a  v  a2  s  . com*/
    method.setEntity(entity);

    HttpResponse response = conn.execute(method);
    assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);

    CourseVO vo = conn.parse(response, CourseVO.class);
    assertNotNull(vo);
    assertNotNull(vo.getRepoEntryKey());
    assertNotNull(vo.getKey());
    return vo;
}

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

public static <T extends ImageBaseModel> String multiPart(String url, T imageUpload, Long equipmentId,
        Long userId, Long equipmentHistoryId, LocationDTOInterface locationDTOLib) throws IOException {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);/*ww  w .  j a v a  2s .c  o m*/
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    String result = "";
    if (imageUpload != null) {
        File file = new File(((ImageUploadModel) imageUpload).getRealUri());
        String imageType = getTypeOfImage(((ImageUploadModel) imageUpload).getRealUri()).toUpperCase();
        String imageName = ConstantImage.IMAGE_NAME;
        Gson gson = new Gson();
        String json = gson.toJson(locationDTOLib);
        mpEntity = addParamsForUpload(file, imageType, imageName, equipmentId, userId, json,
                equipmentHistoryId);

        httppost.setEntity(mpEntity);
        HttpResponse response;
        response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = GalleryUtils.convertStreamToString(instream);
            instream.close();
        }
    }
    return result;
    //        if (imageUploads != null && imageUploads.size() != 0)
    //        {
    ////            for (T imageUpload : imageUploads)
    ////            {
    ////                File file = new File(((ImageUploadModel) imageUpload).getRealUri());
    ////                mpEntity.addPart(ConstantImage.IMAGE_FILE + imageUploads.indexOf(imageUpload), new FileBody(file));
    ////                mpEntity.addPart(ConstantImage.IMAGE_TYPE + imageUploads.indexOf(imageUpload), new StringBody(getTypeOfImage(((ImageUploadModel) imageUpload).getRealUri()).toUpperCase()));
    ////                mpEntity.addPart(ConstantImage.IMAGE_NAME + imageUploads.indexOf(imageUpload), new StringBody(ConstantImage.IMAGE_NAME + imageUploads.indexOf(imageUpload)));
    ////            }
    ////            mpEntity.addPart(ConstantImage.EQUIPMENT_ID, new StringBody(equipmentId.toString()));
    ////            mpEntity.addPart(ConstantImage.USER_ID, new StringBody(userId.toString()));
    ////            LocationDTOLib locationDTOLib = new LocationDTOLib();
    ////            locationDTOLib.setLatitude(BigDecimal.valueOf(0));
    ////            locationDTOLib.setLongitude(BigDecimal.valueOf(0));
    ////            locationDTOLib.setStreet("Street");
    ////            Gson gson = new Gson();
    ////            String json = gson.toJson(locationDTOLib);
    ////            mpEntity.addPart(ConstantImage.IMAGE_LOCATION_DTO, new StringBody(json));
    ////        }
    ////        httppost.setEntity(mpEntity);
    ////        HttpResponse response;
    ////        response = httpclient.execute(httppost);
    ////        HttpEntity entity = response.getEntity();
    ////        String result = "";
    ////        if (entity != null)
    ////        {
    ////            InputStream instream = entity.getContent();
    ////            result = GalleryUtils.convertStreamToString(instream);
    ////            instream.close();
    ////        }
    //
}

From source file:com.norconex.committer.gsa.GsaCommitter.java

@Override
protected void commitBatch(List<ICommitOperation> batch) {

    File xmlFile = null;//  w ww.  j  a  v a 2s  .  c  o m
    try {
        xmlFile = File.createTempFile("batch", ".xml");
        FileOutputStream fout = new FileOutputStream(xmlFile);
        XmlOutput xmlOutput = new XmlOutput(fout);
        Map<String, Integer> stats = xmlOutput.write(batch);
        fout.close();

        HttpPost post = new HttpPost(feedUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("data", xmlFile, ContentType.APPLICATION_XML, xmlFile.getName());
        builder.addTextBody("datasource", "GSA_Commiter");
        builder.addTextBody("feedtype", "full");

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = httpclient.execute(post);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new CommitterException("Invalid response to Committer HTTP request. " + "Response code: "
                    + status.getStatusCode() + ". Response Message: " + status.getReasonPhrase());
        }
        LOG.info("Sent " + stats.get("docAdded") + " additions and " + stats.get("docRemoved")
                + " removals to GSA");

    } catch (Exception e) {
        throw new CommitterException("Cannot index document batch to GSA.", e);
    } finally {
        FileUtils.deleteQuietly(xmlFile);
    }
}

From source file:com.grouzen.android.serenity.HttpConnection.java

private HttpResponse post(String url, Bundle params) throws ClientProtocolException, IOException {
    HttpPost method = new HttpPost(url);

    if (params != null) {
        try {/* w  ww  . j av  a  2  s . c  o  m*/
            if (mMultipartKey != null && mMultipartFileName != null) {
                ByteArrayBody byteArrayBody = new ByteArrayBody(params.getByteArray(mMultipartKey),
                        mMultipartFileName);
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Charset charset = Charset.forName(CHARSET);

                entity.addPart(mMultipartKey, byteArrayBody);
                params.remove(mMultipartKey);

                for (String k : params.keySet()) {
                    entity.addPart(new FormBodyPart(k, new StringBody(params.getString(k), charset)));
                }

                method.setEntity(entity);
            } else {
                ArrayList<NameValuePair> entity = convertParams(params);

                method.setEntity(new UrlEncodedFormEntity(entity, CHARSET));

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return execute(method);
}

From source file:com.impetus.ankush.agent.action.impl.UploadHandler.java

/**
 * Method that builds the multi-part form data request.
 * //w w w.j a va  2s  . c  o  m
 * @param urlString
 *            the urlString to which the file needs to be uploaded
 * @param file
 *            the actual file instance that needs to be uploaded
 * @param fileName
 *            name of the file, just to show how to add the usual form
 *            parameters
 * @param fileDescription
 *            some description for the file, just to show how to add the
 *            usual form parameters
 * @return server response as <code>String</code>
 */
public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {

    HttpPost postRequest = new HttpPost(urlString);
    try {

        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // The usual form parameters can be added this way
        multiPartEntity.addPart("fileDescription",
                new StringBody(fileDescription != null ? fileDescription : ""));
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));

        /*
         * Need to construct a FileBody with the file that needs to be
         * attached and specify the mime type of the file. Add the fileBody
         * to the request as an another part. This part will be considered
         * as file part and the rest of them as usual form-data parts
         */
        FileBody fileBody = new FileBody(file, "application/octect-stream");
        multiPartEntity.addPart("file", fileBody);

        postRequest.setEntity(multiPartEntity);

    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return null;
    }

    return executeRequest(postRequest);
}

From source file:dk.kasperbaago.JSONHandler.JSONHandler.java

public String getURL() {

    //Making a HTTP client
    HttpClient client = new DefaultHttpClient();

    //Declaring HTTP response
    HttpResponse response = null;/*  w w  w  . j  av  a  2  s  .  co  m*/
    String myReturn = null;

    try {

        //Making a HTTP getRequest or post request
        if (method == "get") {
            String parms = "";
            if (this.parameters.size() > 0) {
                parms = "?";
                parms += URLEncodedUtils.format(this.parameters, "utf-8");
            }

            Log.i("parm", parms);
            Log.i("URL", this.url + parms);
            HttpGet getUrl = new HttpGet(this.url + parms);

            //Executing the request
            response = client.execute(getUrl);
        } else if (method == "post") {
            HttpPost getUrl = new HttpPost(this.url);

            //Sets parameters to add
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (int i = 0; i < this.parameters.size(); i++) {
                if (this.parameters.get(i).getName().equalsIgnoreCase(fileField)) {
                    entity.addPart(parameters.get(i).getName(),
                            new FileBody(new File(parameters.get(i).getValue())));
                } else {
                    entity.addPart(parameters.get(i).getName(), new StringBody(parameters.get(i).getName()));
                }
            }

            getUrl.setEntity(entity);

            //Executing the request
            response = client.execute(getUrl);
        } else {
            return "false";
        }

        //Returns the data      
        HttpEntity content = response.getEntity();
        InputStream mainContent = content.getContent();
        myReturn = this.convertToString(mainContent);
        this.HTML = myReturn;
        Log.i("Result", myReturn);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return myReturn;
}

From source file:org.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static String sendPostWithFile(String url, List<NameValuePair> nameValuePairs,
        Map<String, String> fileMap, Context mCtx) {
    HttpPost post = new HttpPost(url);
    HttpClient httpClient = getSSLHttpClient(mCtx);
    // Post???NameValuePair[]
    // ???request.getParameter("name")
    // List<NameValuePair> params = new ArrayList<NameValuePair>();
    // params.add(new BasicNameValuePair("name", data));
    // post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse httpResponse = null;/*from   www  . j  a  v a2 s  .c  o m*/
    // HttpClient httpClient = null;
    post.setHeader("Accept", "*/*");
    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // // ?HTTP request
        for (int index = 0; index < nameValuePairs.size(); index++) {

            entity.addPart(nameValuePairs.get(index).getName(),
                    new StringBody(nameValuePairs.get(index).getValue(), Charset.forName("UTF-8")));

        }
        if (fileMap != null) {
            Iterator iterator = fileMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = (Entry<String, String>) iterator.next();
                File file = new File(entry.getValue());
                entity.addPart(entry.getKey(), new FileBody(file));
            }
        }

        // post.setEntity(new UrlEncodedFormEntity(nameValuePairs,
        // HTTP.UTF_8));

        post.setEntity(entity);
        // ?HTTP response
        // httpClient = getSSLHttpClient();
        httpResponse = httpClient.execute(post);
        // ??200 ok
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            return EntityUtils.toString(httpResponse.getEntity());
        }

    } catch (ClientProtocolException e) {

        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (post != null) {
            post.abort();
            post = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitPicHelper.java

private TwitPicStatus uploadToTwitPic() {
    try {//from w  w  w  .  j  a v a2s .  c om
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));

        if (file == null) {
            // only the input stream was sent, so we need to convert it to a file
            Log.v("talon_twitpic", "converting to file from input stream");
            String filePath = saveStreamTemp(stream);
            file = new File(filePath);
        } else {
            Log.v("talon_twitpic", "already have the file, going right to send it");
        }

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("key", new StringBody(TWITPIC_API_KEY));
        entity.addPart("media", new FileBody(file));
        entity.addPart("message", new StringBody(message));

        Log.v("talon_twitpic", "uploading now");

        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line;
        String url = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            Log.v("talon_twitpic", line);
            builder.append(line);
        }

        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            url = jsonObject.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitpic", "url: " + url);
        Log.v("talon_twitpic", "message: " + message);

        return new TwitPicStatus(message, url);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.datacleaner.actions.PublishFileToMonitorActionListener.java

@Override
protected Map<?, ?> doInBackground() throws Exception {

    final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();

    final String uploadUrl = getUploadUrl(monitorConnection);
    logger.debug("Upload url: {}", uploadUrl);

    final HttpPost request = new HttpPost(uploadUrl);

    final long expectedSize = getExpectedSize();

    publish(new Task() {
        @Override//from   ww w . j  a  v a2  s  . co  m
        public void execute() throws Exception {
            _progressWindow.setExpectedSize(getTransferredFilename(), expectedSize);
        }
    });

    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    final ContentBody uploadFilePart = new AbstractContentBody("application/octet-stream") {

        @Override
        public String getCharset() {
            return null;
        }

        @Override
        public String getTransferEncoding() {
            return MIME.ENC_BINARY;
        }

        @Override
        public long getContentLength() {
            return expectedSize;
        }

        @Override
        public void writeTo(OutputStream out) throws IOException {
            long progress = 0;
            try (final InputStream in = getTransferStream()) {
                byte[] tmp = new byte[4096];
                int length;
                while ((length = in.read(tmp)) != -1) {
                    out.write(tmp, 0, length);

                    // update the visual progress
                    progress = progress + length;

                    final long updatedProgress = progress;

                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _progressWindow.setProgress(getTransferredFilename(), updatedProgress);
                        }
                    });
                }
                out.flush();
            }
        }

        @Override
        public String getFilename() {
            return getTransferredFilename();
        }
    };

    entity.addPart("file", uploadFilePart);
    request.setEntity(entity);

    try (final MonitorHttpClient monitorHttpClient = monitorConnection.getHttpClient()) {
        final HttpResponse response;
        try {
            response = monitorHttpClient.execute(request);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        final StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == 200) {
            logger.info("Upload response status: {}", statusLine);

            // parse the response as a JSON map
            final InputStream content = response.getEntity().getContent();
            final String contentString;
            try {
                contentString = FileHelper.readInputStreamAsString(content, FileHelper.DEFAULT_ENCODING);
            } finally {
                FileHelper.safeClose(content);
            }

            final ObjectMapper objectMapper = new ObjectMapper();
            try {
                final Map<?, ?> responseMap = objectMapper.readValue(contentString, Map.class);

                return responseMap;
            } catch (Exception e) {
                logger.warn("Received non-JSON response:\n{}", contentString);
                logger.error("Failed to parse response as JSON", e);
                return null;
            }
        } else {
            logger.warn("Upload response status: {}", statusLine);
            final String reasonPhrase = statusLine.getReasonPhrase();
            WidgetUtils.showErrorMessage("Server reported error",
                    "Server replied with status " + statusLine.getStatusCode() + ":\n" + reasonPhrase);
            return null;
        }
    }
}