Example usage for org.apache.http.entity.mime MultipartEntityBuilder addTextBody

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addTextBody

Introduction

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

Prototype

public MultipartEntityBuilder addTextBody(final String name, final String text, final ContentType contentType) 

Source Link

Usage

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private String performHttpRequestToBKU(String xmlRequest, RequestPackage pack, SignParameter parameter)
        throws ClientProtocolException, IOException, IllegalStateException {
    CloseableHttpClient client = null;//  ww  w  .  j av a 2  s.  c  o  m
    try {
        client = buildHttpClient();
        HttpPost post = new HttpPost(this.bkuUrl);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setCharset(Charset.forName("UTF-8"));
        entityBuilder.addTextBody(XMLREQUEST, xmlRequest,
                ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8")));

        if (parameter != null) {
            String transactionId = parameter.getTransactionId();
            if (transactionId != null) {
                entityBuilder.addTextBody("TransactionId_", transactionId);
            }
        }

        if (pack != null && pack.getSignatureData() != null) {
            entityBuilder.addBinaryBody("fileupload",
                    PDFUtils.blackOutSignature(pack.getSignatureData(), pack.getByteRange()));
        }
        post.setEntity(entityBuilder.build());

        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());

        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;
            Header[] headers = response.getAllHeaders();

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue());
                    logger.debug("Response Header : {}", hdr.toString());
                    if (hdr.toString().contains("Server")) {
                        BaseSLConnector.responseHeader = hdr.toString();
                    }

                    holder.getProcessInfo().add(hdr);

                }

            }

            BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE);
            logger.debug("Response Header : {}", hdr.toString());

            holder.getProcessInfo().add(hdr);

        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        response = null;
        rd = null;

        logger.trace(result.toString());
        return result.toString();
    } catch (PDFIOException e) {
        throw new PdfAsWrappedIOException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:hspc.submissionsprogram.AppDisplay.java

AppDisplay() {
    this.setTitle("Dominion High School Programming Contest");
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    this.setResizable(false);

    WindowListener exitListener = new WindowAdapter() {
        @Override//from   w ww. j  a va2  s  .  co  m
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
    this.addWindowListener(exitListener);

    JTabbedPane pane = new JTabbedPane();
    this.add(pane);

    JPanel submitPanel = new JPanel(null);
    submitPanel.setPreferredSize(new Dimension(500, 500));

    UIManager.put("FileChooser.readOnly", true);
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setBounds(0, 0, 500, 350);
    fileChooser.setVisible(true);
    FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java");
    fileChooser.setFileFilter(javaFilter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setControlButtonsAreShown(false);
    submitPanel.add(fileChooser);

    JSeparator separator1 = new JSeparator();
    separator1.setBounds(12, 350, 476, 2);
    separator1.setForeground(new Color(122, 138, 152));
    submitPanel.add(separator1);

    JLabel problemChooserLabel = new JLabel("Problem:");
    problemChooserLabel.setBounds(12, 360, 74, 25);
    submitPanel.add(problemChooserLabel);

    String[] listOfProblems = Main.Configuration.get("problem_names")
            .split(Main.Configuration.get("name_delimiter"));
    JComboBox problems = new JComboBox<>(listOfProblems);
    problems.setBounds(96, 360, 393, 25);
    submitPanel.add(problems);

    JButton submit = new JButton("Submit");
    submit.setBounds(170, 458, 160, 30);
    submit.addActionListener(e -> {
        try {
            File file = fileChooser.getSelectedFile();
            try {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url"));

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN);
                builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()),
                        ContentType.TEXT_PLAIN);
                builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
                HttpEntity multipart = builder.build();

                uploadFile.setEntity(multipart);

                CloseableHttpResponse response = httpClient.execute(uploadFile);
                HttpEntity responseEntity = response.getEntity();
                String inputLine;
                BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
                try {
                    if ((inputLine = br.readLine()) != null) {
                        int rowIndex = Integer.parseInt(inputLine);
                        new ResultWatcher(rowIndex);
                    }
                    br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (NullPointerException ex) {
            JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        }
    });
    submitPanel.add(submit);

    JPanel clarificationsPanel = new JPanel(null);
    clarificationsPanel.setPreferredSize(new Dimension(500, 500));

    cList = new JList<>();
    cList.setBounds(12, 12, 476, 200);
    cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    cList.setBackground(new Color(254, 254, 255));
    clarificationsPanel.add(cList);

    JButton viewC = new JButton("View");
    viewC.setBounds(12, 224, 232, 25);
    viewC.addActionListener(e -> {
        if (cList.getSelectedIndex() != -1) {
            int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]);
            clarificationDatas.stream().filter(data -> data.getId() == id).forEach(
                    data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse()));
        }
    });
    clarificationsPanel.add(viewC);

    JButton refreshC = new JButton("Refresh");
    refreshC.setBounds(256, 224, 232, 25);
    refreshC.addActionListener(e -> updateCList(true));
    clarificationsPanel.add(refreshC);

    JSeparator separator2 = new JSeparator();
    separator2.setBounds(12, 261, 476, 2);
    separator2.setForeground(new Color(122, 138, 152));
    clarificationsPanel.add(separator2);

    JLabel problemChooserLabelC = new JLabel("Problem:");
    problemChooserLabelC.setBounds(12, 273, 74, 25);
    clarificationsPanel.add(problemChooserLabelC);

    JComboBox problemsC = new JComboBox<>(listOfProblems);
    problemsC.setBounds(96, 273, 393, 25);
    clarificationsPanel.add(problemsC);

    JTextArea textAreaC = new JTextArea();
    textAreaC.setLineWrap(true);
    textAreaC.setWrapStyleWord(true);
    textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    textAreaC.setBackground(new Color(254, 254, 255));

    JScrollPane areaScrollPane = new JScrollPane(textAreaC);
    areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setBounds(12, 312, 477, 134);
    clarificationsPanel.add(areaScrollPane);

    JButton submitC = new JButton("Submit Clarification");
    submitC.setBounds(170, 458, 160, 30);
    submitC.addActionListener(e -> {
        if (textAreaC.getText().length() > 2048) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        } else if (textAreaC.getText().length() < 20) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.",
                    "Error", JOptionPane.WARNING_MESSAGE);
        } else {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                Class.forName(JDBC_DRIVER);

                conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"),
                        Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass"));

                String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)";
                stmt = conn.prepareStatement(sql);

                stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID)));
                stmt.setString(2, String.valueOf(problemsC.getSelectedItem()));
                stmt.setString(3, String.valueOf(textAreaC.getText()));

                textAreaC.setText("");

                stmt.executeUpdate();

                stmt.close();
                conn.close();

                updateCList(false);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
            }
        }
    });
    clarificationsPanel.add(submitC);

    pane.addTab("Submit", submitPanel);
    pane.addTab("Clarifications", clarificationsPanel);

    Timer timer = new Timer();
    TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            updateCList(false);
        }
    };
    timer.schedule(updateTask, 10000, 10000);

    updateCList(false);

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Create a multipart form/*from  w w w . jav  a2 s .co  m*/
 * 
 * @param request
 *            Request object
 * @param keyVals
 *            Key and value pairs, the even(begins with 0) position params
 *            are key and the odds are values
 * @return
 */
public static HttpUriRequest multipartForm(HttpPost request, Object... keyVals) {
    if (request == null || ValidationUtils.isEmpty(keyVals))
        return request;
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    boolean hasVal = false;

    String key;
    for (int i = 0; i < keyVals.length; i += 2) {
        key = ShenStrings.str(keyVals[i]);
        hasVal = i + 1 < keyVals.length;

        if (!hasVal || keyVals[i + 1] == null) {
            builder.addTextBody(key, StringUtils.EMPTY, CONTENT_TYPE_PLAIN_TEXT);
            break;
        }

        if (keyVals[i + 1].getClass().isAssignableFrom(File.class)) {
            builder.addPart(key, new FileBody((File) keyVals[i + 1]));
        } else {
            builder.addTextBody(key, keyVals[i + 1].toString(), CONTENT_TYPE_PLAIN_TEXT);
        }
    }
    request.setEntity(builder.build());
    return request;
}

From source file:io.swagger.client.api.DefaultApi.java

/**
 * Token endpoint// w  w  w .jav a 2  s .c o m
 * The token endpoint is used to obtain access tokens which allow clients to make API requests
 * @param authorization Basic authorization token (&#39;Basic &lt;client_key&gt;&#39;)
 * @param grantType Grant type used to obtain the token.
 * @param acceptLanguage Client locale, as &lt;language&gt;-&lt;country&gt;
 * @param contentType application/json
 * @param deviceId Device identifier, must uniquely identify the user or device accessing the API. Required only for \&quot;device_credentials\&quot; grant type
 * @param refreshToken Refresh token, used to issue a new token without resending client credentials. Required only for \&quot;refresh_token\&quot; grant type
 * @return AccessToken
 */
public AccessToken postToken(String authorization, String grantType, String acceptLanguage, String contentType,
        String deviceId, String refreshToken) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'authorization' is set
    if (authorization == null) {
        throw new ApiException(400, "Missing the required parameter 'authorization' when calling postToken");
    }

    // verify the required parameter 'grantType' is set
    if (grantType == null) {
        throw new ApiException(400, "Missing the required parameter 'grantType' when calling postToken");
    }

    // create path and map variables
    String localVarPath = "/token".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> localVarHeaderParams = new HashMap<String, String>();
    // form params
    Map<String, String> localVarFormParams = new HashMap<String, String>();

    localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "grant_type", grantType));

    localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization));
    localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage));
    localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType));

    String[] localVarContentTypes = { "application/json" };
    String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json";

    if (localVarContentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        if (deviceId != null) {
            localVarBuilder.addTextBody("device_id", ApiInvoker.parameterToString(deviceId),
                    ApiInvoker.TEXT_PLAIN_UTF8);
        }

        if (refreshToken != null) {
            localVarBuilder.addTextBody("refresh_token", ApiInvoker.parameterToString(refreshToken),
                    ApiInvoker.TEXT_PLAIN_UTF8);
        }

        localVarPostBody = localVarBuilder.build();
    } else {
        // normal form params
        localVarFormParams.put("device_id", ApiInvoker.parameterToString(deviceId));
        localVarFormParams.put("refresh_token", ApiInvoker.parameterToString(refreshToken));
    }

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams,
                localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType);
        if (localVarResponse != null) {
            return (AccessToken) ApiInvoker.deserialize(localVarResponse, "", AccessToken.class);
        } else {
            return null;
        }
    } catch (ApiException ex) {
        throw ex;
    }
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

@VisibleForTesting
void applyToEntityBuilder(String key, Object value, Charset charset, MultipartEntityBuilder entityBuilder) {
    if (value != null) {
        if (value instanceof String) {
            String text = (String) value;
            entityBuilder.addTextBody(key, text, ContentType.create("*/*", charset));
        } else if (value instanceof File) {
            File file = (File) value;
            entityBuilder.addBinaryBody(key, file);
        } else {/*from   w  ww  . j  a  v a 2 s .co m*/
            String canonicalName = value.getClass().getCanonicalName();
            throw new UnsupportedOperationException("No Handler found for " + canonicalName
                    + ". Only String or File is accepted, " + "because http parameters knows no other types.");
        }
    }
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

private HttpEntity buildParts(BaseRequest request) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) {
        if (h.getFileName() == null) {
            if (h.isContentTypeSet()) {
                builder.addTextBody(h.getPartName(), new String(h.getBodyAsString()),
                        ContentType.create(h.getContentType()));
            } else {
                builder.addTextBody(h.getPartName(), new String(h.getBodyAsString()));
            }//from  ww  w .  j  ava 2 s .c  om
        } else {
            if (h.isContentTypeSet()) {
                builder.addBinaryBody(h.getPartName(), h.getBody(), ContentType.create(h.getContentType()),
                        h.getFileName());
            } else {
                builder.addBinaryBody(h.getFileName(), h.getBody());
            }
        }
    }
    return builder.build();
}

From source file:org.openscore.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        httpEntity = new UrlEncodedFormEntity(list, contentType.getCharset());
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/*w w w  .  j  a  va  2s.  c  om*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        Charset charset = contentType != null ? contentType.getCharset() : null;
        httpEntity = new UrlEncodedFormEntity(list, charset);
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/*from   ww  w.ja v a2 s  .  c  om*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input,
        String fileName, final long fileSize) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*from  ww w .ja v  a 2 s  .  c  o m*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add auth part to the multipart entity
    auth = StringUtils.trimToNull(auth);
    if (auth != null) {
        //StringBody authPart = new StringBody(
        //  auth, ContentType.create( "text/plain", getEncoding() ) );
        //b.addPart( "auth", authPart );
        b.addTextBody("auth", auth, ContentType.create("text/plain", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";
        //InputStreamBody filePart = new InputStreamBody( input, fileName );
        InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize);
        b.addPart("videofile", filePart);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.setHeader("MIME-Version", "1.0");
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept-Charset", "UTF-8");
    request.setHeader("Accept-Encoding", "gzip,deflate");
    request.setHeader("Connection", "close");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    //getAuthConsumer().sign( request );

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input,
        String fileName, String mimeType) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;//w  w w  .j a  va2  s  .  co  m
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add xml part to the multipart entity
    if (xml != null) {
        //InputStreamBody xmlPart = new InputStreamBody(
        //  new ByteArrayInputStream( xml.getBytes( getEncoding() ) ),
        //  ContentType.parse( "application/xml" ),
        //  "body.xml" );
        //b.addPart( "metadata", xmlPart );
        b.addTextBody("metadata", xml, ContentType.create("application/xml", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        mimeType = StringUtils.trimToNull(mimeType);
        if (mimeType == null)
            mimeType = "application/octet-stream";

        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";

        //InputStreamBody filePart = new InputStreamBody(
        //  input, ContentType.create( mimeType ), fileName );
        //b.addPart( "attachment", filePart );
        b.addBinaryBody("attachment", input, ContentType.create(mimeType), fileName);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept", "application/xml");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    getAuthConsumer().sign(request);

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}