Example usage for org.apache.http.entity.mime FormBodyPart FormBodyPart

List of usage examples for org.apache.http.entity.mime FormBodyPart FormBodyPart

Introduction

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

Prototype

public FormBodyPart(final String name, final ContentBody body) 

Source Link

Usage

From source file:neembuu.uploader.uploaders.common.FormBodyPartUtils.java

/**
 * Create an empty form body part./*from   ww  w  .  j  a  v a  2s .co m*/
 * @param name the name of the field.
 * @param body the content of the field.
 * @return Return the new empty form body part.
 * @throws UnsupportedEncodingException 
 */
public static FormBodyPart createEmptyFileFormBodyPart(final String name, StringBody body)
        throws UnsupportedEncodingException {
    return new FormBodyPart(name, body) {
        @Override
        protected void generateContentDisp(final ContentBody body) {
            StringBuilder buffer = new StringBuilder();
            buffer.append("form-data; name=\"").append(name).append("\"");
            buffer.append("; filename=\"\"");
            buffer.append("\n");
            addField(MIME.CONTENT_DISPOSITION, buffer.toString());
            addField(MIME.CONTENT_TYPE, "application/octet-stream");
        }

    };
}

From source file:org.jcommon.com.facebook.utils.FacebookRequest.java

public void run() {
    HttpClient httpclient = new DefaultHttpClient();
    try {//  ww w  .ja  v a  2 s  . c o  m
        logger.info(Integer.valueOf("file size:" + this.in != null ? this.in.available() : 0));
        HttpPost httppost = new HttpPost(this.url_);
        MultipartEntity reqEntity = new MultipartEntity();

        FormBodyPart stream_part = new FormBodyPart(this.stream_name,
                new InputStreamBody(this.in, this.file_name));

        reqEntity.addPart(stream_part);
        for (int i = 0; i < this.keys.length; i++) {
            reqEntity.addPart(this.keys[i], new StringBody(this.values[i]));
        }

        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        StatusLine status_line = response.getStatusLine();
        int responseCode = status_line.getStatusCode();

        BufferedReader http_reader = null;
        if (responseCode == 200) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            if (this.listener_ != null)
                this.listener_.onSuccessful(this, this.sResult);
        } else if (responseCode >= 400) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            logger.info("[URL][response][failure]" + this.sResult);
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
        } else {
            this.sResult.append("[URL][response][failure][code : " + responseCode + " ]");
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
            logger.info("[URL][response][failure][code : " + responseCode + " ]");
        }
        EntityUtils.consume(resEntity);
    } catch (UnsupportedEncodingException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (ClientProtocolException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (IOException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:org.apache.abdera2.protocol.client.MultipartRelatedEntity.java

public MultipartRelatedEntity(Entry entry, ContentBody other, String contentType, String boundary) {
    if (entry == null || other == null)
        throw new IllegalArgumentException();
    this.boundary = boundary != null ? boundary : String.valueOf(System.currentTimeMillis());
    this.contentType = new BasicHeader("Content-Type", String.format(
            "Multipart/Related; boundary=\"%s\";type=\"%s\"", this.boundary, Helper.getMimeType(entry)));
    String cs = entry.getDocument().getCharset();
    Charset charset = cs != null ? Charset.forName(cs) : Charset.defaultCharset();
    multipart = new HttpMultipart("related", charset, this.boundary, HttpMultipartMode.STRICT);
    multipart.addBodyPart(new FormBodyPart("entry", new AbderaBody(entry)));
    String contentId = entry.getContentSrc().toString();
    if (!contentId.matches("cid\\:.+")) {
        throw new IllegalArgumentException("entry content source is not a correct content-ID");
    }/* www.  j a  va  2  s  .c om*/
    FormBodyPart other_part = new FormBodyPart("other", other);
    other_part.addField("Content-ID", String.format("<%s>", contentId.substring(4)));
    other_part.addField("Content-Type", other.getMimeType());
    multipart.addBodyPart(other_part);
}

From source file:com.rackspace.api.clients.veracode.DefaultVeracodeApiClient.java

private String uploadFile(File file, int buildVersion, String appId, String platfrom)
        throws VeracodeApiException {
    HttpPost post = new HttpPost(baseUri.resolve(UPLOAD));

    MultipartEntity entity = new MultipartEntity();

    try {/*from  ww w. ja v a  2  s.c o  m*/
        entity.addPart(new FormBodyPart("app_id", new StringBody(appId)));
        entity.addPart(new FormBodyPart("version", new StringBody(String.valueOf(buildVersion))));
        entity.addPart(new FormBodyPart("platform", new StringBody(platfrom)));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("The Request could not be made due to an encoding issue", e);

    }

    entity.addPart("file", new FileBody(file, "text/plain"));

    post.setEntity(entity);

    logger.println("Executing Request: " + post.getRequestLine());

    UploadResponse uploadResponse = null;

    try {
        uploadResponse = new UploadResponse(client.execute(post));
    } catch (IOException e) {
        throw new VeracodeApiException("The call to Veracode failed.", e);
    }

    return uploadResponse.getBuildId(buildVersion);
}

From source file:com.app.precared.utils.MultipartEntityBuilder.java

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) {
    Args.notNull(name, "Name");
    Args.notNull(contentBody, "Content body");
    return addPart(new FormBodyPart(name, contentBody));
}

From source file:org.apache.manifoldcf.agents.output.solr.ModifiedMultipartEntity.java

public void addPart(final String name, final ContentBody contentBody) {
    addPart(new FormBodyPart(name, contentBody));
}

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   www.  j a  va2  s .  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.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   ww w .ja v a  2s . co  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.ctctlabs.ctctwsjavalib.CTCTConnection.java

/**
 * Perform a multipart post request to the web service
 * @param link     URL to perform the post request
 * @param content  the string part//  ww  w  .j  a v  a  2s . c  o  m
 * @param baData   the byte array part
 * @param fileName the file name in the byte array part
 * @return response entity content returned by the web service
 * @throws ClientProtocolException
 * @throws IOException
 * @author CL Kim
 */
InputStream doPostMultipartRequest(String link, String content, byte[] baData, String fileName)
        throws ClientProtocolException, IOException {
    HttpPost httppost = new HttpPost(link);

    StringBody sbody = new StringBody(content);
    FormBodyPart fbp1 = new FormBodyPart("imageatomxmlpart", sbody);
    fbp1.addField("Content-Type", "application/atom+xml");
    //fbp1.addField("Accept", "application/atom+xml");

    ByteArrayBody babody = new ByteArrayBody(baData, fileName);
    FormBodyPart fbp2 = new FormBodyPart("imagejpegpart", babody);
    fbp2.addField("Content-Type", "image/jpeg");
    fbp2.addField("Transfer-Encoding", "binary");
    //fbp2.addField("Accept", "application/atom+xml");

    MultipartEntity reqEntity = new MultipartEntity(); // HttpMultipartMode.STRICT is default, cannot be HttpMultipartMode.BROWSER_COMPATIBLE
    reqEntity.addPart(fbp1);
    reqEntity.addPart(fbp2);
    httppost.setEntity(reqEntity);
    if (accessToken != null)
        httppost.setHeader("Authorization", "Bearer " + accessToken); // for OAuth2.0
    HttpResponse response = httpclient.execute(httppost);

    if (response != null) {
        responseStatusCode = response.getStatusLine().getStatusCode();
        responseStatusReason = response.getStatusLine().getReasonPhrase();
        // If receive anything but a 201 status, return a null input stream
        if (responseStatusCode == HttpStatus.SC_CREATED) {
            return response.getEntity().getContent();
        }
        return null;
    } else {
        responseStatusCode = 0; // reset to initial default
        responseStatusReason = null; // reset to initial default
        return null;
    }
}

From source file:iqq.im.service.ApacheHttpService.java

@Override
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {/*w w w.  j  ava2 s  .c o m*/
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}