Example usage for org.apache.commons.httpclient.methods.multipart StringPart setTransferEncoding

List of usage examples for org.apache.commons.httpclient.methods.multipart StringPart setTransferEncoding

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods.multipart StringPart setTransferEncoding.

Prototype

public void setTransferEncoding(String paramString) 

Source Link

Usage

From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java

/**
 * // ww w .  j  ava 2 s .co  m
 * 
 * @param filename
 */
public void upload(String filename, QQUser user) {
    HttpClient client = new HttpClient();
    HostConfiguration conf = new HostConfiguration();
    conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD);
    client.setHostConfiguration(conf);
    PostMethod method = new PostMethod("/cgi-bin/cface/upload");
    method.addRequestHeader("Accept", "*/*");
    method.addRequestHeader("Pragma", "no-cache");

    StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ()));
    uid.setContentType(null);
    uid.setTransferEncoding(null);

    //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7");
    //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040");
    StringPart clientkey = new StringPart("clientkey",
            "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67");
    //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16");
    //      StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey()));
    clientkey.setContentType(null);
    clientkey.setTransferEncoding(null);

    //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875");
    //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62");
    //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA");
    StringPart sign = new StringPart("sign",
            "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764");
    sign.setContentType(null);
    sign.setTransferEncoding(null);

    FilePart file;
    try {
        file = new FilePart("customfacefile", filename, new File(filename));
    } catch (FileNotFoundException e) {
        return;
    }

    Part[] parts = new Part[] { uid, clientkey, sign, file };
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());

    method.setRequestEntity(entity);
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            Header header = method.getResponseHeader("CFace-Msg");
            System.out.println(header.getValue());
            header = method.getResponseHeader("CFace-RetCode");
            System.out.println(header.getValue());
        }
    } catch (HttpException e) {
        return;
    } catch (IOException e) {
        return;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java

private StringPart createStringPart(String name, String value) {
    StringPart stringPart = new StringPart(name, value);
    stringPart.setContentType(null);//from   w  w w . j a  v  a2s  . co m
    stringPart.setTransferEncoding(null);
    stringPart.setCharSet("UTF-8");
    return stringPart;
}

From source file:games.strategy.triplea.pbem.AxisAndAlliesForumPoster.java

/**
 * Utility method for creating string parts, since we need to remove transferEncoding and content type to behave like a browser
 * /*  ww  w  .j a v a  2  s . c  o  m*/
 * @param name
 *            the form field name
 * @param value
 *            the for field value
 * @return return the created StringPart
 */
private StringPart createStringPart(final String name, final String value) {
    final StringPart stringPart = new StringPart(name, value);
    stringPart.setTransferEncoding(null);
    stringPart.setContentType(null);
    return stringPart;
}

From source file:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java

@Override
public void transmit(SLResult slResult) throws IOException {
    log.trace("Sending data.");
    if (urlEncoded) {
        ////  w ww.j av  a  2  s.c  om
        // application/x-www-form-urlencoded (legacy, SL < 1.2)
        //

        OutputStream os = connection.getOutputStream();
        OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET);

        // ResponseType
        streamWriter.write(FORMPARAM_RESPONSETYPE);
        streamWriter.write("=");
        streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8"));
        streamWriter.write("&");

        // XMLResponse / Binary Response
        if (slResult.getResultType() == SLResultType.XML) {
            streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE);
        } else {
            streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE);
        }
        streamWriter.write("=");
        streamWriter.flush();
        URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter);
        slResult.writeTo(new StreamResult(urlEnc), false);
        urlEnc.flush();

        // transfer parameters
        char[] cbuf = new char[512];
        int len;
        for (HTTPFormParameter formParameter : httpFormParameter) {
            streamWriter.write("&");
            streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8"));
            streamWriter.write("=");
            InputStreamReader reader = new InputStreamReader(formParameter.getData(),
                    (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was
                                                                                                                                                                            // application/x-www-form-urlencoded,
                                                                                                                                                                            // formParam therefore UTF-8
            while ((len = reader.read(cbuf)) != -1) {
                urlEnc.write(cbuf, 0, len);
            }
            urlEnc.flush();
        }
        streamWriter.close();

    } else {
        //
        // multipart/form-data (conforming to SL 1.2)
        //

        ArrayList<Part> parts = new ArrayList<Part>();

        // ResponseType
        StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8");
        responseType.setTransferEncoding(null);
        parts.add(responseType);

        // XMLResponse / Binary Response
        SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING);
        if (slResult.getResultType() == SLResultType.XML) {
            slResultPart.setTransferEncoding(null);
            slResultPart.setContentType(slResult.getMimeType());
            slResultPart.setCharSet(XML_RESPONSE_ENCODING);
        } else {
            slResultPart.setTransferEncoding(null);
            slResultPart.setContentType(slResult.getMimeType());
        }
        parts.add(slResultPart);

        // transfer parameters
        for (HTTPFormParameter formParameter : httpFormParameter) {
            InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData());
            FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(),
                    formParameter.getCharSet());
            part.setTransferEncoding(formParameter.getTransferEncoding());
            parts.add(part);
        }

        OutputStream os = connection.getOutputStream();
        Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes());
        os.close();

    }

    // MultipartRequestEntity PostMethod
    InputStream is = null;
    try {
        is = connection.getInputStream();
    } catch (IOException iox) {
        log.info("Failed to get InputStream of HTTPUrlConnection.", iox);
    }
    log.trace("Reading response.");
    response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is);
    Map<String, String> responseHttpHeaders = new HashMap<String, String>();
    Map<String, List<String>> httpHeaders = connection.getHeaderFields();
    for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) {
        String key = keyIt.next();
        StringBuffer value = new StringBuffer();
        for (String val : httpHeaders.get(key)) {
            value.append(val);
            value.append(HttpUtil.SEPARATOR[0]);
        }
        String valString = value.substring(0, value.length() - 1);
        if ((key != null) && (value.length() > 0)) {
            responseHttpHeaders.put(key, valString);
        }
    }
    response.setResponseHttpHeaders(responseHttpHeaders);
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach)
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        authenticate();/*from  w  w w. jav  a  2 s .c  om*/
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach,
        IProgressMonitor monitor)/*  w  w w .  j  av a2 s .  co  m*/
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        monitor.subTask("Authenticating request");
        authenticate();
        if (checkMonitor(monitor))
            return null;
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    monitor.subTask("Sending request");
    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:JiraWebClient.java

public void attachFile(final JiraIssue issue, final String comment, final FilePart filePart,
        final String contentType, IProgressMonitor monitor) throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override//from   w  ww  .j  a  v a  2  s  .  co  m
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder attachFileURLBuffer = new StringBuilder(baseUrl);
            attachFileURLBuffer.append("/secure/AttachFile.jspa"); //$NON-NLS-1$

            PostMethod post = new PostMethod(attachFileURLBuffer.toString());
            prepareSecurityToken(post);

            List<PartBase> parts = new ArrayList<PartBase>();

            StringPart idPart = new StringPart("id", issue.getId()); //$NON-NLS-1$
            StringPart commentLevelPart = new StringPart("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$

            // The transfer encodings have to be removed for some reason
            // There is no need to send the content types for the strings,
            // as they should be in the correct format
            idPart.setTransferEncoding(null);
            idPart.setContentType(null);

            if (comment != null) {
                StringPart commentPart = new StringPart("comment", comment); //$NON-NLS-1$
                commentPart.setTransferEncoding(null);
                commentPart.setContentType(null);
                commentPart.setCharSet(client.getCharacterEncoding(monitor));
                parts.add(commentPart);
            }

            commentLevelPart.setTransferEncoding(null);
            commentLevelPart.setContentType(null);

            filePart.setTransferEncoding(null);
            if (contentType != null) {
                filePart.setContentType(contentType);
            }
            parts.add(filePart);
            parts.add(idPart);
            parts.add(commentLevelPart);

            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));

            try {
                execute(post);
                if (!expectRedirect(post, "/secure/ManageAttachments.jspa?id=" + issue.getId())) { //$NON-NLS-1$
                    handleErrorMessage(post);
                }
            } finally {
                post.releaseConnection();
            }
        }
    });
}

From source file:com.foglyn.fogbugz.FogBugzClient.java

private StringPart stringPart(String name, String value) {
    // FogBugz doesn't like when we set Content-Type or Transfer-Enconding headers for part
    // It also always expects text encoded in UTF-8
    StringPart p = new StringPart(name, value, "UTF-8");
    p.setContentType(null);//w w w . j a  v  a 2 s. c o  m
    p.setTransferEncoding(null);
    return p;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

private String sendPostData(PostMethod post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        String contentEncoding = getContentEncoding();
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;// w ww  .  j  av  a2s .c  o m
        }

        final boolean browserCompatible = getDoBrowserCompatibleMultipart();
        // We don't know how many entries will be skipped
        List<PartBase> partlist = new ArrayList<>();
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding);
            if (browserCompatible) {
                part.setTransferEncoding(null);
                part.setContentType(null);
            }
            partlist.add(part);
        }

        // Add any files
        for (HTTPFileArg file : files) {
            File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            // We do not know the char set of the file to be uploaded, so we set it to null
            ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(),
                    null);
            filePart.setCharSet(null); // We do not know what the char set of the file is
            partlist.add(filePart);
        }

        // Set the multipart for the post
        int partNo = partlist.size();
        Part[] parts = partlist.toArray(new Part[partNo]);
        MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(multiPart);

        // Set the content type
        String multiPartContentType = multiPart.getContentType();
        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType);

        // If the Multipart is repeatable, we can send it first to
        // our own stream, without the actual file content, so we can return it
        if (multiPart.isRepeatable()) {
            // For all the file multiparts, we must tell it to not include
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos);
                }
            }
            // Write the request to our own stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multiPart.writeRequest(bos);
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();

            // For all the file multiparts, we must revert the hiding of
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(false);
                }
            }
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }
    } else {
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null);
            post.setRequestEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            String contentEncoding = getContentEncoding();
            boolean haveContentEncoding = false;
            if (isNullOrEmptyTrimmed(contentEncoding)) {
                contentEncoding = null;
            } else {
                post.getParams().setContentCharset(contentEncoding);
                haveContentEncoding = true;
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    String value;
                    if (haveContentEncoding) {
                        value = arg.getEncodedValue(contentEncoding);
                    } else {
                        value = arg.getEncodedValue();
                    }
                    postBody.append(value);
                }
                StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(),
                        post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding);
                post.setRequestEntity(requestEntity);
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        String urlContentEncoding = contentEncoding;
                        if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                            // Use the default encoding for urls
                            urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                        }
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    post.addParameter(parameterName, parameterValue);
                }

                /*
                //                    // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2
                //                    // sends the same post body.
                //
                //                    // Only include the content char set in the content-type header if it is not
                //                    // an APPLICATION_X_WWW_FORM_URLENCODED content type
                //                    String contentCharSet = null;
                //                    if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) {
                //                        contentCharSet = post.getRequestCharSet();
                //                    }
                //                    StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet);
                //                    post.setRequestEntity(requestEntity);
                */
            }

            // If the request entity is repeatable, we can send it first to
            // our own stream, so we can return it
            if (post.getRequestEntity().isRepeatable()) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                post.getRequestEntity().writeRequest(bos);
                bos.flush();
                // We get the posted bytes using the encoding used to create it
                postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet()));
                bos.close();
            } else {
                postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
            }
        }
    }
    // Set the content length
    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
            Long.toString(post.getRequestEntity().getContentLength()));

    return postedBody.toString();
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebClient.java

public void attachFile(final JiraIssue issue, final String comment, final FilePart filePart,
        final String contentType, IProgressMonitor monitor) throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*from www .  j a va 2s .c o m*/
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder attachFileURLBuffer = new StringBuilder(baseUrl);
            attachFileURLBuffer.append("/secure/AttachFile.jspa"); //$NON-NLS-1$

            PostMethod post = new PostMethod(attachFileURLBuffer.toString());

            List<PartBase> parts = new ArrayList<PartBase>();

            StringPart idPart = new StringPart("id", issue.getId()); //$NON-NLS-1$
            StringPart commentLevelPart = new StringPart("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$

            // The transfer encodings have to be removed for some reason
            // There is no need to send the content types for the strings,
            // as they should be in the correct format
            idPart.setTransferEncoding(null);
            idPart.setContentType(null);

            if (comment != null) {
                StringPart commentPart = new StringPart("comment", comment); //$NON-NLS-1$
                commentPart.setTransferEncoding(null);
                commentPart.setContentType(null);
                parts.add(commentPart);
            }

            commentLevelPart.setTransferEncoding(null);
            commentLevelPart.setContentType(null);

            filePart.setTransferEncoding(null);
            if (contentType != null) {
                filePart.setContentType(contentType);
            }
            parts.add(filePart);
            parts.add(idPart);
            parts.add(commentLevelPart);

            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));

            try {
                execute(post);
                if (!expectRedirect(post, "/secure/ManageAttachments.jspa?id=" + issue.getId())) { //$NON-NLS-1$
                    handleErrorMessage(post);
                }
            } finally {
                post.releaseConnection();
            }
        }
    });
}