Example usage for org.apache.http.entity.mime MultipartEntity addPart

List of usage examples for org.apache.http.entity.mime MultipartEntity addPart

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:fedroot.dacs.http.DacsPostRequest.java

/**
 * the following, which includes parameters in the multipart entity is not grokked
 * by DACS multipart parsing/*from  w w  w  .j av a 2 s . com*/
 * @param webServiceRequest
 * @return
 */
private HttpPost multipartBrokenPost(WebServiceRequest webServiceRequest) {
    try {
        HttpPost multipartPost = new HttpPost(webServiceRequest.getBaseURI());
        //            multipartPost.setHeader("Content-Type", webServiceRequest.getEnclosureType());
        multipartPost.setHeader("Content-Transfer-Encoding", "7bit");
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                "----HttpClientBoundarynSbUMwsZpJVNlFYK", Charset.forName("US-ASCII"));

        for (NameValuePair nameValuePair : webServiceRequest.getNameValuePairs()) {
            multipartEntity.addPart(nameValuePair.getName(),
                    new StringBody(new String(nameValuePair.getValue().getBytes(), Charset.forName("US-ASCII")),
                            Charset.forName("US-ASCII")));
        }
        for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) {
            multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody());
        }
        multipartPost.setEntity(multipartEntity);
        return multipartPost;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage());
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.client.HttpImageUploadChannel.java

/**
 * Create a post request encapsulating bytes from the given
 * ByteArrayOutputStream.//from  w w  w  .j a v  a2s.c om
 */
private HttpPost setupRequest(ByteArrayOutputStream bos) {
    ContentBody cb = new ByteArrayBody(bos.toByteArray(), "image");
    HttpPost postRequest = new HttpPost(uri + "/uploadImage");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    // add a single part to the request
    reqEntity.addPart("file", cb);
    postRequest.setEntity(reqEntity);

    return postRequest;
}

From source file:org.fedoraproject.eclipse.packager.bodhi.api.BodhiClient.java

@Override
public BodhiLoginResponse login(String username, String password) throws BodhiClientLoginException {
    BodhiLoginResponse result = null;/*  ww w  .j  a  v a2  s .co  m*/
    try {
        HttpPost post = new HttpPost(getLoginUrl());
        // Add "Accept: application/json" HTTP header
        post.addHeader(ACCEPT_HTTP_HEADER_NAME, MIME_JSON);

        // Construct the multipart POST request body.
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(LOGIN_PARAM_NAME, new StringBody(LOGIN_PARAM_VALUE));
        reqEntity.addPart(USERNAME_PARAM_NAME, new StringBody(username));
        reqEntity.addPart(PASSWORD_PARAM_NAME, new StringBody(password));

        post.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity resEntity = response.getEntity();
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new BodhiClientLoginException(NLS.bind("{0} {1}", response.getStatusLine().getStatusCode(), //$NON-NLS-1$
                    response.getStatusLine().getReasonPhrase()), response);
        } else {
            // Got a 200, response body is the JSON passed on from the
            // server.
            String jsonString = ""; //$NON-NLS-1$
            if (resEntity != null) {
                try {
                    jsonString = parseResponse(resEntity);
                } catch (IOException e) {
                    // ignore
                } finally {
                    EntityUtils.consume(resEntity); // clean up resources
                }
            }
            // log JSON string if in debug mode
            if (PackagerPlugin.inDebugMode()) {
                FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance();
                logger.logInfo(NLS.bind(BodhiText.BodhiClient_rawJsonStringMsg, jsonString));
            }
            // Deserialize from JSON
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeDeserializer());
            Gson gson = gsonBuilder.create();
            result = gson.fromJson(jsonString, BodhiLoginResponse.class);
        }
    } catch (IOException e) {
        throw new BodhiClientLoginException(e.getMessage(), e);
    }
    return result;
}

From source file:face4j.ResponderImpl.java

/**
 * @see {@link Responder#doPost(File, URI, List)}
 *///  w  ww  .j  a v a 2  s. c o m
public String doPost(final File file, final URI uri, final List<NameValuePair> params)
        throws FaceClientException, FaceServerException {
    try {
        final MultipartEntity entity = new MultipartEntity();

        if (logger.isInfoEnabled()) {
            logger.info("Adding image entity, size: [{}] bytes", file.length());
        }

        entity.addPart("image", new FileBody(file));

        try {
            for (NameValuePair nvp : params) {
                entity.addPart(nvp.getName(), new StringBody(nvp.getValue()));
            }
        }

        catch (UnsupportedEncodingException uee) {
            logger.error("Error adding entity", uee);
            throw new FaceClientException(uee);
        }

        postMethod.setURI(uri);
        postMethod.setEntity(entity);

        final long start = System.currentTimeMillis();
        final HttpResponse response = httpClient.execute(postMethod);

        if (logger.isDebugEnabled()) {
            logger.debug("POST took {} (ms)", (System.currentTimeMillis() - start));
        }

        return checkResponse(response);
    }

    catch (IOException ioe) {
        logger.error("Error while POSTing to {} ", uri, ioe);
        throw new FaceClientException(ioe);
    }
}

From source file:org.openbmap.soapclient.FileUploader.java

/**
 * @param file/* w w w . j av a 2 s  .co  m*/
 * @return
 */
private boolean performUpload(final String file) {
    // TODO check network state
    // @see http://developer.android.com/training/basics/network-ops/connecting.html

    // Adjust HttpClient parameters
    final HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    //HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

    final HttpPost httppost = new HttpPost(mServer);
    try {

        final String authorizationString = "Basic "
                + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP);
        httppost.setHeader("Authorization", authorizationString);

        final MultipartEntity entity = new MultipartEntity();

        // TODO we don't need passwords for the new service
        entity.addPart(LOGIN_FIELD, new StringBody(mUser));
        entity.addPart(PASSWORD_FIELD, new StringBody(mPassword));
        entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml"));

        httppost.setEntity(entity);
        final HttpResponse response = httpclient.execute(httppost);

        final int reply = response.getStatusLine().getStatusCode();
        if (reply == 200) {
            Log.i(TAG, "Uploaded " + file + ": Server reply " + reply);
        } else {
            Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply);
        }
        // everything is ok if we receive HTTP 200
        // TODO: redirects (301, 302) are NOT handled here 
        // thus if something changes on the server side we're dead here
        return (reply == HttpStatus.SC_OK);
    } catch (final ClientProtocolException e) {
        Log.e(TAG, e.getMessage());
    } catch (final IOException e) {
        Log.e(TAG, "I/O exception on file " + file);
    }
    return false;
}

From source file:mydropbox.Client.java

public boolean sendFile(String fileName) throws IOException {
    int status = 0;
    Timestamp temp_timestamp = new Timestamp(System.currentTimeMillis());
    long timestamp = temp_timestamp.getTime();
    File file = new File("./files/" + fileName);
    HttpPost httpPost = new HttpPost(this.host + "upload" + '/' + timestamp);

    MultipartEntity mpEntity = new MultipartEntity();

    ContentBody cbFile = new FileBody(file);
    mpEntity.addPart(file.getName(), cbFile);

    httpPost.setEntity(mpEntity);//w  w  w.j a v a2  s .c  o m
    System.out.println("executing request " + httpPost.getRequestLine());
    HttpResponse response;

    try {
        httpPost.setHeader("User-Agent", USER_AGENT);
        httpPost.setHeader("MyDropBox", "MyDropBox");

        response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());
        status = response.getStatusLine().getStatusCode();
        System.out.println("Response Code : " + status);
        System.out.println(EntityUtils.toString(resEntity));

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        setTimeStamp(timestamp);
    }
    if (status >= 200 && status < 300)
        return true;
    else
        return false;
}

From source file:com.nominanuda.web.http.ServletHelper.java

@SuppressWarnings("unchecked")
private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength,
        String ct, String cenc) throws IOException {
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        try {/* w  w  w  . j a v a  2  s.co m*/
            items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) {
                public ServletInputStream getInputStream() throws IOException {
                    return new ServletInputStream() {
                        public int read() throws IOException {
                            return is.read();
                        }

                        public int read(byte[] arg0) throws IOException {
                            return is.read(arg0);
                        }

                        public int read(byte[] b, int off, int len) throws IOException {
                            return is.read(b, off, len);
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isFinished() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isReady() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public void setReadListener(ReadListener arg0) {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                        }
                    };
                }
            });
        } catch (FileUploadException e) {
            throw new IOException(e);
        }
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (FileItem i : items) {
            multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName()));
        }
        return multipartEntity;
    } else {
        InputStreamEntity entity = new InputStreamEntity(is, contentLength);
        entity.setContentType(ct);
        if (cenc != null) {
            entity.setContentEncoding(cenc);
        }
        return entity;
    }
}

From source file:org.sonar.plugins.web.markup.validation.MarkupValidator.java

/**
 * Post contents of HTML file to the W3C validation service. In return, receive a Soap response message.
 *
 * @see http://validator.w3.org/docs/api.html
 *//*from w  w  w  . jav  a2 s.  c  o  m*/
private void postHtmlContents(InputFile inputfile) {

    HttpPost post = new HttpPost(validationUrl);
    HttpResponse response = null;

    post.addHeader("User-Agent", "sonar-w3c-markup-validation-plugin/1.0");

    try {

        LOG.info("W3C Validate: " + inputfile.getRelativePath());

        // file upload
        MultipartEntity multiPartRequestEntity = new MultipartEntity();
        String charset = CharsetDetector.detect(inputfile.getFile());
        FileBody fileBody = new FileBody(inputfile.getFile(), TEXT_HTML_CONTENT_TYPE, charset);
        multiPartRequestEntity.addPart(UPLOADED_FILE, fileBody);

        // set output format
        multiPartRequestEntity.addPart(OUTPUT, new StringBody(SOAP12));

        post.setEntity(multiPartRequestEntity);
        response = executePostMethod(post);

        // write response to report file
        if (response != null) {
            writeResponse(response, inputfile);
        }

    } catch (UnsupportedEncodingException e) {
        LOG.error(e);
    } finally {
        // release any connection resources used by the method
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException ioe) {
                LOG.debug(ioe);
            }
        }
    }
}

From source file:org.fedoraproject.eclipse.packager.bodhi.api.BodhiClient.java

@Override
public BodhiUpdateResponse createNewUpdate(String[] builds, String release, String type, String request,
        String bugs, String notes, String csrfToken, boolean suggestReboot, boolean enableKarmaAutomatism,
        int stableKarmaThreshold, int unstableKarmaThreshold, boolean closeBugsWhenStable)
        throws BodhiClientException {
    try {/*w w w . java2  s . c  o m*/
        HttpPost post = new HttpPost(getPushUpdateUrl());
        post.addHeader(ACCEPT_HTTP_HEADER_NAME, MIME_JSON);

        StringBuffer buildsNVR = new StringBuffer();
        for (int i = 0; i < (builds.length - 1); i++) {
            buildsNVR.append(builds[i]);
            buildsNVR.append(BUILDS_DELIMITER);
        }
        buildsNVR.append(builds[(builds.length - 1)]);
        String buildsParamValue = buildsNVR.toString();

        // Construct the multipart POST request body.
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(BUILDS_PARAM_NAME, new StringBody(buildsParamValue));
        reqEntity.addPart(TYPE_PARAM_NAME, new StringBody(type));
        reqEntity.addPart(REQUEST_PARAM_NAME, new StringBody(request));
        reqEntity.addPart(BUGS_PARAM_NAME, new StringBody(bugs));
        reqEntity.addPart(CSRF_PARAM_NAME, new StringBody(csrfToken));
        reqEntity.addPart(AUTOKARMA_PARAM_NAME, new StringBody(String.valueOf(enableKarmaAutomatism)));
        reqEntity.addPart(NOTES_PARAM_NAME, new StringBody(notes));
        reqEntity.addPart(SUGGEST_REBOOT, new StringBody(String.valueOf(suggestReboot)));
        reqEntity.addPart(STABLE_KARMA, new StringBody(String.valueOf(stableKarmaThreshold)));
        reqEntity.addPart(UNSTABLE_KARMA, new StringBody(String.valueOf(unstableKarmaThreshold)));
        reqEntity.addPart(CLOSE_BUGS_WHEN_STABLE, new StringBody(String.valueOf(closeBugsWhenStable)));

        post.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity resEntity = response.getEntity();
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new BodhiClientException(NLS.bind("{0} {1}", response.getStatusLine().getStatusCode(), //$NON-NLS-1$
                    response.getStatusLine().getReasonPhrase()), response);
        } else {
            String rawJsonString = ""; //$NON-NLS-1$
            if (resEntity != null) {
                try {
                    rawJsonString = parseResponse(resEntity);
                } catch (IOException e) {
                    // ignore
                }
                EntityUtils.consume(resEntity); // clean up resources
            }
            // log JSON string if in debug mode
            if (PackagerPlugin.inDebugMode()) {
                FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance();
                logger.logInfo(NLS.bind(BodhiText.BodhiClient_rawJsonStringMsg, rawJsonString));
            }
            // deserialize the result from the JSON response
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            BodhiUpdateResponse result = gson.fromJson(rawJsonString, BodhiUpdateResponse.class);
            return result;
        }
    } catch (IOException e) {
        throw new BodhiClientException(e.getMessage(), e);
    }
}