Example usage for org.apache.http.entity.mime.content StringBody StringBody

List of usage examples for org.apache.http.entity.mime.content StringBody StringBody

Introduction

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

Prototype

public StringBody(final String text, final String mimeType, Charset charset)
            throws UnsupportedEncodingException 

Source Link

Usage

From source file:eu.trentorise.opendata.jackan.test.ckan.ExperimentalCkanClient.java

/**
 * Uploads a file using file storage api, which I think is deprecated. As of
 * Aug 2015, coesn't work neither with demo.ckan.org nor dati.trentino
 *
 * Adapted from/* w ww.  j a  v a  2 s .com*/
 * https://github.com/Ontodia/openrefine-ckan-storage-extension/blob/c99de78fd605c4754197668c9396cffd1f9a0267/src/org/deri/orefine/ckan/StorageApiProxy.java#L34
 */
public String uploadFile(String fileContent, String fileLabel) {
    HttpResponse formFields = null;
    try {
        String filekey = null;
        HttpClient client = new DefaultHttpClient();

        //   get the form fields required from ckan storage
        // notice if you put '3/' it gives not found :-/
        String formUrl = getCatalogUrl() + "/api/storage/auth/form/file/" + fileLabel;
        HttpGet getFormFields = new HttpGet(formUrl);
        getFormFields.setHeader("Authorization", getCkanToken());
        formFields = client.execute(getFormFields);
        HttpEntity entity = formFields.getEntity();
        if (entity != null) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            entity.writeTo(os);

            //now parse JSON
            //JSONObject obj = new JSONObject(os.toString());
            JsonNode obj = new ObjectMapper().readTree(os.toString());

            //post the file now
            String uploadFileUrl = getCatalogUrl() + obj.get("action").asText();
            HttpPost postFile = new HttpPost(uploadFileUrl);
            postFile.setHeader("Authorization", getCkanToken());
            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT);

            //JSONArray fields = obj.getJSONArray("fields");
            Iterator<JsonNode> fields = obj.get("fields").elements();
            while (fields.hasNext()) {
                JsonNode fieldObj = fields.next();
                //JSONObject fieldObj = fields.getJSONObject(i);
                String fieldName = fieldObj.get("name").asText();
                String fieldValue = fieldObj.get("value").asText();
                if (fieldName.equals("key")) {
                    filekey = fieldValue;
                }
                mpEntity.addPart(fieldName,
                        new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8")));
            }

            /*
             for (int i = 0; i < fields.length(); i++) {
             //JSONObject fieldObj = fields.getJSONObject(i);
             JSONObject fieldObj = fields.getJSONObject(i);
             String fieldName = fieldObj.getString("name");
             String fieldValue = fieldObj.getString("value");
             if (fieldName.equals("key")) {
             filekey = fieldValue;
             }
             mpEntity.addPart(fieldName, new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8")));                    
             }
             */
            //   assure that we got the file key
            if (filekey == null) {
                throw new RuntimeException(
                        "failed to get the file key from CKAN storage form API. the response from " + formUrl
                                + " was: " + os.toString());
            }

            //the file should be the last part
            //hack... StringBody didn't work with large files
            mpEntity.addPart("file", new ByteArrayBody(fileContent.getBytes(Charset.forName("UTF-8")),
                    "multipart/form-data", fileLabel));

            postFile.setEntity(mpEntity);

            HttpResponse fileUploadResponse = client.execute(postFile);

            //check if the response status code was in the 200 range
            if (fileUploadResponse.getStatusLine().getStatusCode() < 200
                    || fileUploadResponse.getStatusLine().getStatusCode() >= 300) {
                throw new RuntimeException("failed to add the file to CKAN storage. response status line from "
                        + uploadFileUrl + " was: " + fileUploadResponse.getStatusLine());
            }
            return getCatalogUrl() + "/storage/f/" + filekey;

            //return CKAN_STORAGE_FILES_BASE_URI + filekey;
        }
        throw new RuntimeException("failed to get form details from CKAN storage. response line was: "
                + formFields.getStatusLine());
    } catch (IOException ioe) {
        throw new RuntimeException("failed to upload file to CKAN Storage ", ioe);
    }
}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequest() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*from   w  w  w. jav a2 s .c  om*/
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
        HttpPost post = new HttpPost(uri);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                StandardCharsets.UTF_8);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n"
                + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n"
                + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n"
                + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n",
                response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:eu.liveGov.libraries.livegovtoolkit.Utils.RestClient.java

public void Execute(RequestMethod method, int soTime, int connTime) throws Exception {
    switch (method) {
    case GET: {//  www .  j  a v  a2  s.  c om
        // add parameters
        String combinedParams = "";
        if (!params.isEmpty()) {
            combinedParams += "?";
            for (NameValuePair p : params) {
                String paramString;
                paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");

                if (combinedParams.length() > 1) {
                    combinedParams += "&" + paramString;
                } else {
                    combinedParams += paramString;
                }
            }
        }

        HttpGet request = new HttpGet(url + combinedParams);

        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        executeRequest(request, url, soTime, connTime);
        break;
    }
    case POST: {
        HttpPost request = new HttpPost(url);

        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }
        if (!_json.isEmpty()) {
            request.addHeader("Content-type", "application/json");
            request.setEntity(new StringEntity(_json, "UTF8"));

        } else if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        }

        executeRequest(request, url, soTime, connTime);
        break;
    }
    case POSTLOG: {
        HttpPost request = new HttpPost(url);

        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        MultipartEntity reqEntity = new MultipartEntity();

        if (!_json.isEmpty()) {
            reqEntity.addPart("LogfileRequest",
                    new StringBody(_json, "application/json", Charset.forName("UTF-8")));
        } else if (!params.isEmpty()) {
            // ignore the params for now.
        }

        if (_file != null) {
            reqEntity.addPart("logfile", new FileBody(_file));
        }

        request.setEntity(reqEntity);

        executeRequest(request, url, soTime, connTime);
        break;
    }
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.CommandService.java

private static HttpResp<Void> sendCommandWithMedia(final Context ctx, CommandObject cmd)
        throws KurentoCommandException, TransportException, InvalidDataException, NotFoundException {
    String contentPath = cmd.getMedia();

    File content = new File(contentPath);
    String mimeType;//from  ww w.  j  a  v a 2s .co m
    if (content.exists() && content.isFile()) {
        if (contentPath.contains(ConstantKeys.EXTENSION_JPG)) {
            mimeType = ConstantKeys.TYPE_IMAGE;
        } else {
            mimeType = ConstantKeys.TYPE_VIDEO;
        }
    } else {
        String error = contentPath + " does not exists or is not a file";
        log.error(error);
        throw new KurentoCommandException(error);
    }

    CustomMultiPartEntity mpEntity;
    final String json = cmd.getJson();
    String charset = HTTP.UTF_8;
    long contentSize = 0;
    try {
        contentSize = content.length();
        /* Aprox. total size */
        final long totalSize = content.length() + json.getBytes("UTF-16BE").length;
        mpEntity = new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener() {

            private int i;

            @Override
            public void transferred(long num) {
                int totalpercent = Math.min(100, (int) ((num * 100) / totalSize));

                if (totalpercent > (1 + PERCENT_INC * i) || totalpercent >= 100) {
                    Intent intent = new Intent();
                    intent.setAction(ConstantKeys.BROADCAST_PROGRESSBAR);
                    intent.putExtra(ConstantKeys.JSON, json);
                    intent.putExtra(ConstantKeys.TOTAL, totalpercent);
                    ctx.sendBroadcast(intent);
                    i++;
                }
            }
        });

        mpEntity.addPart(COMMAND_PART_NAME,
                new StringBody(json, HttpManager.CONTENT_TYPE_APPLICATION_JSON, Charset.forName(charset)));

        FormBodyPart fbp = new FormBodyPart(CONTENT_PART_NAME, new FileBody(content, mimeType));
        fbp.addField(HTTP.CONTENT_LEN, String.valueOf(contentSize));
        mpEntity.addPart(fbp);

    } catch (UnsupportedEncodingException e) {
        String msg = "Cannot use " + charset + "as entity";
        log.error(msg, e);
        throw new TransportException(msg);
    }

    return HttpManager.sendPostVoid(ctx, ctx.getString(R.string.url_command), mpEntity);
}

From source file:com.ibm.watson.developer_cloud.document_conversion.v1.helpers.ConvertDocumentHelper.java

/**
 * Synchronously converts a new document without persistence
 * POST /v1/convert_document.//  www.  jav a  2s .co  m
 *
 * @param document The file to convert
 * @param mediaType Internet media type for the file
 * @param conversionTarget The conversion target to use
 * @return Converted document in the specified format
 * @see DocumentConversion#convertDocument(File, String, ConversionTarget)
 */
public InputStream convertDocument(final File document, String mediaType,
        final ConversionTarget conversionTarget) {
    if (mediaType == null || mediaType.isEmpty())
        throw new IllegalArgumentException("media type cannot be null or empty");
    if (!ConversionUtils.isValidMediaType(mediaType))
        throw new IllegalArgumentException("file with the given media type is not supported");
    if (document == null || !document.exists())
        throw new IllegalArgumentException("document can not be null and must exist");
    if (conversionTarget == null)
        throw new IllegalArgumentException("conversion target can not be null");

    try {
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", new FileBody(document, mediaType));
        JsonObject configRequestJson = new JsonObject();
        configRequestJson.addProperty("conversion_target", conversionTarget.toString());
        String json = configRequestJson.toString();
        reqEntity.addPart("config", new StringBody(json, MediaType.APPLICATION_JSON, Charset.forName("UTF-8")));

        HttpRequestBase request = Request.Post(ConfigConstants.CONVERT_DOCUMENT_PATH).withEntity(reqEntity)
                .build();

        HttpResponse response = docConversionService.execute(request);
        InputStream is = ResponseUtil.getInputStream(response);
        return is;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

public MultipartEntity createMultipartEntity(FileBody fileBody, String mimeType, int sampleRate) {
    // see: http://stackoverflow.com/questions/3014633
    //MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);

    try {//from  ww w  .j  a  v a  2  s  .co m
        entity.addPart("email", new StringBody(mEmail, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("MODEL_SAMPLE_RATE",
                new StringBody(String.valueOf(sampleRate), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("DECODING", new StringBody(mDecodingSpeed, "text/plain", Charset.forName("UTF-8")));
        String sendEmailAsString = "0";
        if (mIsSendEmail) {
            sendEmailAsString = "1";
        }
        entity.addPart("SEND_EMAIL", new StringBody(sendEmailAsString, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("upload_wav", fileBody);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return entity;
}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequestWithAddedServlet() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {//from ww  w .  j a v a  2s  .co  m
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/added";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n"
                + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n"
                + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n"
                + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n",
                response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

@Test
public void testFileUploadWithEagerParsing() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {//  w  w  w . j av  a  2  s.co m

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(
                new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.servoy.extensions.plugins.http.BaseEntityEnclosingRequest.java

@Override
protected HttpEntity buildEntity() throws Exception {
    HttpEntity entity = null;//w w  w. j  a va  2  s.com
    if (files.size() == 0) {
        if (params != null) {
            entity = new UrlEncodedFormEntity(params, charset);
        } else if (!Utils.stringIsEmpty(content)) {
            entity = new StringEntity(content, mimeType, charset);
            content = null;
        }
    } else if (files.size() == 1 && (params == null || params.size() == 0)) {
        Object f = files.values().iterator().next();
        if (f instanceof File) {
            entity = new FileEntity((File) f, ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else if (f instanceof JSFile) {
            entity = new InputStreamEntity(((JSFile) f).getAbstractFile().getInputStream(),
                    ((JSFile) f).js_size(), ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else {
            Debug.error("could not add file to post request unknown type: " + f);
        }
    } else {
        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        for (Entry<Pair<String, String>, Object> e : files.entrySet()) {
            Object file = e.getValue();
            if (file instanceof File) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new FileBody((File) file));
            } else if (file instanceof JSFile) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(),
                        new ByteArrayBody(
                                Utils.getBytesFromInputStream(
                                        ((JSFile) file).getAbstractFile().getInputStream()),
                                "binary/octet-stream", ((JSFile) file).js_getName()));
            } else {
                Debug.error("could not add file to post request unknown type: " + file);
            }
        }

        // add the parameters
        if (params != null) {
            Iterator<NameValuePair> it = params.iterator();
            while (it.hasNext()) {
                NameValuePair nvp = it.next();
                // For usual String parameters
                ((MultipartEntity) entity).addPart(nvp.getName(),
                        new StringBody(nvp.getValue(), "text/plain", Charset.forName(charset)));
            }
        }
    }

    // entity may have been set already, see PutRequest.js_setFile
    return entity;
}

From source file:ecblast.test.EcblastTest.java

public String atomAtomMappingSMI(String query, String type)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(MultiPartWriter.class);
    Client client = Client.create(cc);//from  w  w  w. j  a v  a 2 s  . c  o  m
    String urlString = "http://localhost:8080/ecblast-rest/aam";
    WebResource webResource = client.resource("http://localhost:8080/ecblast-rest/aam");
    //String smi = "[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12])[CH3:6].[H:30][OH:14]>>[H:30][O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12].[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([OH:14])[CH3:6]";

    FormDataMultiPart form = new FormDataMultiPart();
    switch (type) {
    case "SMI":
        form.field("q", query);
        form.field("Q", "SMI");
        break;
    case "RXN":
        /*MultivaluedMapImpl values = new MultivaluedMapImpl();
        values.add("q", new File(query));
        values.add("Q", "RXN");
        ClientResponse response = webResource.type(MediaType.).post(ClientResponse.class, values);
        return response.toString();
                
        File attachment = new File(query);
                
        FileInputStream fis = null;
                
        fis = new FileInputStream(attachment);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
        bos.write(buf, 0, readNum); //no doubt here is 0
        }
        fis.close();
        bos.close();
        } catch (IOException ex) {
        try {
        fis.close();
        bos.close();
        } catch (IOException e) {
        return "ERROR";
        }
        return "ERROR";
                
        }
        byte[] bytes = bos.toByteArray();
                
        FormDataBodyPart bodyPart = new FormDataBodyPart("q", new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM_TYPE);
        form.bodyPart(bodyPart);
        //form.field("q", bodyPart);
        //form.field*
        form.field("Q", "RXN", MediaType.MULTIPART_FORM_DATA_TYPE);*/
        DefaultHttpClient client1;
        client1 = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(urlString);
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        // FileBody queryFileBody = new FileBody(queryFile);
        multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : ""));
        //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));
        File file = new File(query);
        FileBody fileBody = new FileBody(file);
        //Prepare payload
        multiPartEntity.addPart("q", fileBody);
        multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client1.execute(postRequest);
        return response.toString();
    }
    form.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

    ClientResponse responseJson = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class,
            form);
    return responseJson.toString();
}