Example usage for org.apache.http.entity.mime FormBodyPartBuilder setBody

List of usage examples for org.apache.http.entity.mime FormBodyPartBuilder setBody

Introduction

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

Prototype

public FormBodyPartBuilder setBody(final ContentBody body) 

Source Link

Usage

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) {
    boolean hasNullName = false;
    for (MultiPartItem item : items) {
        if (item.getName() == null) {
            hasNullName = true;//www .  java  2s  .co m
            break;
        }
    }
    if (hasNullName) { // multipart/related
        String boundary = createBoundary();
        String text = getAsStringEntity(items, boundary);
        ContentType ct = ContentType.create(mediaType)
                .withParameters(new BasicNameValuePair("boundary", boundary));
        return new StringEntity(text, ct);
    } else {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setContentType(ContentType.create(mediaType));
        for (MultiPartItem item : items) {
            if (item.getValue() == null || item.getValue().isNull()) {
                logger.warn("ignoring null multipart value for key: {}", item.getName());
                continue;
            }
            String name = item.getName();
            ScriptValue sv = item.getValue();
            if (name == null) {
                // builder.addPart(bodyPart);
            } else {
                FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name);
                ContentBody contentBody;
                switch (sv.getType()) {
                case INPUT_STREAM:
                    InputStream is = (InputStream) sv.getValue();
                    contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name);
                    break;
                case XML:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML);
                    break;
                case JSON:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON);
                    break;
                default:
                    contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN);
                }
                formBuilder = formBuilder.setBody(contentBody);
                builder = builder.addPart(formBuilder.build());
            }
        }
        return builder.build();
    }
}