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, Charset charset) throws UnsupportedEncodingException 

Source Link

Usage

From source file:outfox.ynote.open.client.YNoteHttpUtils.java

/**
 * Do a http post with the multipart content type. This method is usually
 * used to upload the large size content, such as uploading a file.
 *
 * @param url/*from   w  w w. j a v  a  2s  .c o m*/
 * @param formParams
 * @param accessor
 * @return
 * @throws IOException
 * @throws YNoteException
 */
public static HttpResponse doPostByMultipart(String url, Map<String, Object> formParams, OAuthAccessor accessor)
        throws IOException, YNoteException {
    HttpPost post = new HttpPost(url);
    // for multipart encoded post, only sign with the oauth parameters
    // do not sign the our form parameters
    Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.POST, null, accessor);
    if (formParams != null) {
        // encode our ynote parameters
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName("UTF-8"));
        for (Entry<String, Object> parameter : formParams.entrySet()) {
            if (parameter.getValue() instanceof File) {
                // deal with file particular
                entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue()));
            } else if (parameter.getValue() != null) {
                entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(),
                        Charset.forName(YNoteConstants.ENCODING)));
            }
        }
        post.setEntity(entity);
    }
    post.addHeader(oauthHeader);
    HttpResponse response = client.execute(post);
    if ((response.getStatusLine().getStatusCode() / 100) != 2) {
        YNoteException e = wrapYNoteException(response);
        throw e;
    }
    return response;
}

From source file:com.brightcove.zartan.common.helper.MediaAPIHelper.java

/**
 * Executes a file upload write api call against the given URI. This is useful for create_video
 * and add_image//from   ww  w  . j  a v  a  2 s  . com
 * 
 * @param json the json representation of the call you are making
 * @param file the file you are uploading
 * @param uri the api servlet you want to execute against
 * @return json response from api
 * @throws BadEnvironmentException
 * @throws MediaAPIException
 */
public JsonNode executeWrite(JsonNode json, File file, URI uri)
        throws BadEnvironmentException, MediaAPIException {

    mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write");

    HttpPost method = new HttpPost(uri);
    MultipartEntity entityIn = new MultipartEntity();
    FileBody fileBody = null;

    if (file != null) {
        fileBody = new FileBody(file);
    }

    try {
        entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new BadEnvironmentException("UTF-8 no longer supported");
    }

    if (file != null) {
        entityIn.addPart(file.getName(), fileBody);
    }
    method.setEntity(entityIn);

    return executeCall(method);
}

From source file:foam.littlej.android.app.net.ReportsHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *///from  www .jav a 2 s. c  o  m
public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    log("PostFileUpload(): upload file to server.");

    apiUtils.updateDomain();
    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            for (Entry<String, String> en : params.entrySet()) {
                String key = en.getKey();
                if (key == null || "".equals(key)) {
                    continue;
                }
                String val = en.getValue();
                if (!"filename".equals(key)) {
                    entity.addPart(key, new StringBody(val, Charset.forName("UTF-8")));
                    continue;
                }

                if (!TextUtils.isEmpty(val)) {
                    String filenames[] = val.split(",");
                    log("filenames " + ImageManager.getPhotoPath(context, filenames[0]));
                    for (int i = 0; i < filenames.length; i++) {
                        if (ImageManager.getPhotoPath(context, filenames[i]) != null) {
                            File file = new File(ImageManager.getPhotoPath(context, filenames[i]));
                            if (file.exists()) {
                                entity.addPart("incident_photo[]", new FileBody(file));
                            }
                        }
                    }
                }
            }

            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                UshahidiApiResponse resp = GsonHelper.fromStream(respEntity.getContent(),
                        UshahidiApiResponse.class);
                return resp.getErrorCode() == 0;
            }
        }

    } catch (MalformedURLException ex) {
        log("PostFileUpload(): MalformedURLException", ex);

        return false;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        log("IllegalArgumentException", ex);
        // invalid URI
        return false;
    } catch (ConnectTimeoutException ex) {
        //connection timeout
        log("ConnectionTimeoutException");
        return false;
    } catch (SocketTimeoutException ex) {
        log("SocketTimeoutException");
    } catch (IOException e) {
        log("IOException", e);
        // timeout
        return false;
    }
    return false;
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpUpload(String url, String dataFieldName, byte[] data, List<NameValuePair> params) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w  w w. j  av a 2s  .  c om*/
        HttpPost httppost = new HttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody(dataFieldName, data, ContentType.DEFAULT_BINARY, "tempfile");
        for (NameValuePair hp : params) {
            builder.addPart(hp.getName(),
                    new StringBody(hp.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
        }
        HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
        httppost.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(br);
            return je.getAsJsonObject();
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:org.dataconservancy.ui.it.support.DepositRequest.java

public HttpPost asHttpPost() {
    if (!dataSetSet) {
        throw new IllegalStateException("DataItem not set: call setDataSet(DataItem) first.");
    }/*  w  w w  .  j  a v  a 2s  .  c o  m*/

    if (fileToDeposit == null) {
        throw new IllegalStateException("File not set: call setFileToDeposit(File) first");
    }

    if (collectionId == null || collectionId.isEmpty()) {
        throw new IllegalStateException("Collection id not set: call setCollectionId(String) first.");
    }

    if (isUpdate && (dataItemIdentifier == null || dataItemIdentifier.isEmpty())) {
        throw new IllegalStateException(
                "Identifer is not set Identifier must be set: callSetDataSetIdentifier or pass in an ID in the constructor");
    }

    if (null == packageId)
        packageId = "";

    String depositUrl = urlConfig.getDepositUrl().toString()
            + "?redirectUrl=/pages/usercollections.jsp?currentCollectionId=" + collectionId;
    HttpPost post = new HttpPost(depositUrl);
    MultipartEntity entity = new MultipartEntity();
    try {
        entity.addPart("currentCollectionId", new StringBody(collectionId, Charset.forName("UTF-8")));
        entity.addPart("dataSet.name", new StringBody(name, Charset.forName("UTF-8")));
        entity.addPart("dataSet.description", new StringBody(description, Charset.forName("UTF-8")));
        entity.addPart("dataSet.id", new StringBody(dataItemIdentifier, Charset.forName("UTF-8")));
        entity.addPart("depositPackage.id", new StringBody(packageId, Charset.forName("UTF-8")));
        entity.addPart("isContainer",
                new StringBody(Boolean.valueOf(isContainer()).toString(), Charset.forName("UTF-8")));
        if (isUpdate) {
            entity.addPart("datasetToUpdateId", new StringBody(dataItemIdentifier, Charset.forName("UTF-8")));
            entity.addPart(STRIPES_UPDATE_EVENT, new StringBody("Update", Charset.forName("UTF-8")));
        } else {
            entity.addPart(STRIPES_DEPOSIT_EVENT, new StringBody("Deposit", Charset.forName("UTF-8")));
        }

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    FileBody fileBody = new FileBody(fileToDeposit);
    entity.addPart("uploadedFile", fileBody);
    post.setEntity(entity);

    return post;
}

From source file:com.welocalize.dispatcherMW.client.Main.java

public static String uploadXLF(String p_fileName, String p_securityCode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(getFunctinURL(TYPE_UPLOAD, p_securityCode, null));

    try {/* w  ww. j  a v a  2  s  .c  o  m*/
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("fileName", new StringBody(p_fileName, ContentType.create("text/plain", Consts.UTF_8)))
                .addPart("file", new FileBody(new File(p_fileName))).build();
        httpPost.setEntity(reqEntity);

        // send the http request and get the http response
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        String jobID = null;
        String msg = EntityUtils.toString(resEntity);
        if (msg.contains("\"jobID\":\"")) {
            int startIndex = msg.indexOf("\"jobID\":\"");
            jobID = msg.substring(startIndex + 9, msg.indexOf(",", startIndex) - 1);
            System.out.println("Create Job: " + jobID + ", wtih file:" + p_fileName);
            return jobID;
        }

        System.out.println(msg);
        return jobID;
    } catch (Exception e) {
        System.out.println("testHTTPClient error. " + e);
    } finally {
        httpPost.releaseConnection();
    }

    return null;
}

From source file:ch.tatool.app.export.ServerDataExporter.java

private HttpEntity getHttpEntity(Module module, int fromSessionIndex, String filename, File tmpFile) {
    // we use a multipart entity to send over the files
    MultipartEntity entity = new MultipartEntity();

    // get tatool online information for module
    Map<String, String> moduleProperties = module.getModuleProperties();
    String subjectCode = moduleProperties.get(Module.PROPERTY_MODULE_CODE);
    if (subjectCode == null || subjectCode.isEmpty()) {
        subjectCode = module.getUserAccount().getName();
    }/*from   ww  w. j a v a 2  s .c  o m*/

    String moduleID = moduleProperties.get(Module.PROPERTY_MODULE_ID);

    // InputStreamBody does not provide a content length (-1), so the server complains about the request length not
    // being defined. FileBody does not allow setting the name (which is different from the temp file name
    // Easiest solution: subclass of FileBody that allows overwriting the filename with a new one
    FileBodyExt fileBody = new FileBodyExt(tmpFile);
    fileBody.setFilename(filename);
    entity.addPart("file", fileBody);

    // add some additional data
    try {
        Charset utf8CharSet = Charset.forName("UTF-8");
        entity.addPart("fromSessionIndex", new StringBody(String.valueOf(fromSessionIndex), utf8CharSet));
        entity.addPart("subjectCode", new StringBody(subjectCode, utf8CharSet));
        entity.addPart("moduleID", new StringBody(moduleID, utf8CharSet));
    } catch (UnsupportedEncodingException e) {
        // should not happen
        logger.error("Unable to set write form parts", e);
    } catch (IllegalArgumentException e) {
        // should not happen
        logger.error("Missing settings for tatool online", e);
        return null;
    }

    return entity;
}

From source file:io.undertow.servlet.test.security.basic.ServletCertAndDigestAuthTestCase.java

@Test
public void testMultipartRequest() throws Exception {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 2000; i++) {
        sb.append("0123456789");
    }//from  w  w  w  .j a  va  2s  .c o m

    try (TestHttpClient client = new TestHttpClient()) {
        // create POST request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt"));
        builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML));
        HttpEntity entity = builder.build();

        client.setSSLContext(clientSSLContext);
        String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart";
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64
                .encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false));

        HttpResponse result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    }
}

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 w  w  w. jav a  2  s .  com*/
    // 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.grouzen.android.serenity.HttpConnection.java

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

    if (params != null) {
        try {/*from w w  w . ja va  2s  . 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);
}