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

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

Introduction

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

Prototype

public MultipartEntity(final HttpMultipartMode mode) 

Source Link

Usage

From source file:com.socrata.Dataset.java

private JSONObject multipartUpload(String url, File file, String field) {
    HttpPost poster = new HttpPost(httpBase() + url);

    // Makes sure the Content-type is set, otherwise the server chokes
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);

    FileBody fileBody = new FileBody(file);
    reqEntity.addPart(field, fileBody);//from   w w  w  .  j  av  a2s  .  c  om

    poster.setEntity(reqEntity);
    JsonPayload response = performRequest(poster);

    if (isErroneous(response)) {
        log(Level.SEVERE, "Failed to upload file.", null);
        return null;
    }
    return response.getObject();
}

From source file:com.nkang.kxmoment.util.SolrUtils.HttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, final ResponseParser processor)
        throws SolrServerException, IOException {
    HttpRequestBase method = null;// w  ww .  ja  v a  2 s  . c om
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }

    int tries = maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = baseUrl + path;
                    boolean hasNullStreamName = false;
                    if (streams != null) {
                        for (ContentStream cs : streams) {
                            if (cs.getName() == null) {
                                hasNullStreamName = true;
                                break;
                            }
                        }
                    }
                    boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1))
                            && !hasNullStreamName;

                    // only send this list of params as query string params
                    ModifiableSolrParams queryParams = new ModifiableSolrParams();
                    for (String param : this.queryParams) {
                        String[] value = wparams.getParams(param);
                        if (value != null) {
                            for (String v : value) {
                                queryParams.add(param, v);
                            }
                            wparams.remove(param);
                        }
                    }

                    LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
                    if (streams == null || isMultipart) {
                        HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false));
                        post.setHeader("Content-Charset", "UTF-8");
                        if (!isMultipart) {
                            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
                        Iterator<String> iter = wparams.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = wparams.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (isMultipart) {
                                        parts.add(new FormBodyPart(p,
                                                new StringBody(v, Charset.forName("UTF-8"))));
                                    } else {
                                        postParams.add(new BasicNameValuePair(p, v));
                                    }
                                }
                            }
                        }

                        if (isMultipart && streams != null) {
                            for (ContentStream content : streams) {
                                String contentType = content.getContentType();
                                if (contentType == null) {
                                    contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
                                }
                                String name = content.getName();
                                if (name == null) {
                                    name = "";
                                }
                                parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(),
                                        contentType, content.getName())));
                            }
                        }

                        if (parts.size() > 0) {
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                            for (FormBodyPart p : parts) {
                                entity.addPart(p);
                            }
                            post.setEntity(entity);
                        } else {
                            //not using multipart
                            post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(wparams, false);
                        HttpPost post = new HttpPost(url + pstr);

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }

                            });
                        } else {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }
                            });
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if (tries < 1) {
                    throw r;
                }
            }
        }
    } catch (IOException ex) {
        throw new SolrServerException("error reading streams", ex);
    }

    // client already has this set, is this needed
    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    method.addHeader("User-Agent", AGENT);

    // add jauth information
    //String username = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_USERNAME).toString();
    //String password = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_PASSWORD).toString();

    ResourceBundle bundle = ResourceBundle.getBundle("solrconfig");
    String username;
    String password;
    username = bundle.getString("wsUsername.url");
    password = bundle.getString("wsPassword.url");

    method.addHeader("username", username);
    method.addHeader("password", password);

    InputStream respBody = null;
    boolean shouldClose = true;
    boolean success = false;
    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        respBody = response.getEntity().getContent();
        Header ctHeader = response.getLastHeader("content-type");
        String contentType;
        if (ctHeader != null) {
            contentType = ctHeader.getValue();
        } else {
            contentType = "";
        }

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            if (processor == null) {
                throw new RemoteSolrException(httpStatus,
                        "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:"
                                + response.getStatusLine().getReasonPhrase(),
                        null);
            }
        }
        if (processor == null) {

            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<Object>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            success = true;
            return rsp;
        }

        String procCt = processor.getContentType();
        if (procCt != null) {
            String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
            String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
            if (!procMimeType.equals(mimeType)) {
                // unexpected mime type
                String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
                Header encodingHeader = response.getEntity().getContentEncoding();
                String encoding;
                if (encodingHeader != null) {
                    encoding = encodingHeader.getValue();
                } else {
                    encoding = "UTF-8"; // try UTF-8
                }
                try {
                    msg = msg + " " + IOUtils.toString(respBody, encoding);
                } catch (IOException e) {
                    throw new RemoteSolrException(httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null);
                throw e;
            }
        }

        //      if(true) {
        //        ByteArrayOutputStream copy = new ByteArrayOutputStream();
        //        IOUtils.copy(respBody, copy);
        //        String val = new String(copy.toByteArray());
        //        System.out.println(">RESPONSE>"+val+"<"+val.length());
        //        respBody = new ByteArrayInputStream(copy.toByteArray());
        //      }

        NamedList<Object> rsp = null;
        String charset = EntityUtils.getContentCharSet(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, charset);
        } catch (Exception e) {
            throw new RemoteSolrException(httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            String reason = null;
            try {
                NamedList<?> err = (NamedList<?>) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    // TODO? get the trace?
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase());
                msg.append("\n\n");
                msg.append("request: " + method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            throw new RemoteSolrException(httpStatus, reason, null);
        }
        success = true;
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (respBody != null && shouldClose) {
            try {
                respBody.close();
            } catch (IOException e) {
                //log.error("", e);
            } finally {
                if (!success) {
                    method.abort();
                }
            }
        }
    }
}

From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws IOException, UnsupportedOperationException {
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding//from   ww w  .  j  a  va  2  s . c  om

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}

From source file:com.k42b3.neodym.oauth.Oauth.java

@SuppressWarnings("unused")
private HttpEntity httpRequest(String method, String url, Map<String, String> header, String body)
        throws Exception {
    // build request
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpRequestBase request;//from ww  w . j  a  v a 2 s . c  o m

    if (method.equals("GET")) {
        request = new HttpGet(url);
    } else if (method.equals("POST")) {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("text", new StringBody(body));

        request = new HttpPost(url);

        ((HttpPost) request).setEntity(entity);
    } else {
        throw new Exception("Invalid request method");
    }

    // header
    Set<String> keys = header.keySet();

    for (String key : keys) {
        request.setHeader(key, header.get(key));
    }

    // execute HTTP Get Request
    logger.info("Request: " + request.getRequestLine());

    HttpResponse httpResponse = httpClient.execute(request);

    HttpEntity entity = httpResponse.getEntity();

    String responseContent = EntityUtils.toString(entity);

    // log traffic
    if (trafficListener != null) {
        TrafficItem trafficItem = new TrafficItem();

        trafficItem.setRequest(request);
        trafficItem.setResponse(httpResponse);
        trafficItem.setResponseContent(responseContent);

        trafficListener.handleRequest(trafficItem);
    }

    // check status code
    int statusCode = httpResponse.getStatusLine().getStatusCode();

    if (!(statusCode >= 200 && statusCode < 300)) {
        JOptionPane.showMessageDialog(null, responseContent);

        throw new Exception("No successful status code");
    }

    return entity;
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testMultipartPostWithParametersAndPayload() throws Exception {
    HttpPost post = new HttpPost(
            "http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart/123?query=abcd");
    MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT);
    multipart.addPart("part1", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    multipart.addPart("part2", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8")));
    post.setEntity(multipart);/* w  ww. j  a  va2s . c  o m*/
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java

private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException {
    HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml");
    if (isCancelled()) {
        throw new IOException("Fail to execute request due to canceling");
    }//from w w  w .ja va 2  s.  co m

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("name", new StringBody(photo.getName()));
    entity.addPart("track_id", new StringBody(Integer.toString(trackId)));
    //entity.addPart("description", new StringBody(""));
    entity.addPart("file", new FileBody(photo));
    request.setEntity(entity);

    mConsumer.sign(request);
    if (BreadcrumbsAdapter.DEBUG) {
        Log.d(TAG, "Execute request: " + request.getURI());
        for (Header header : request.getAllHeaders()) {
            Log.d(TAG, "   with header: " + header.toString());
        }
    }
    HttpResponse response = mHttpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    InputStream stream = responseEntity.getContent();
    String responseText = XmlCreator.convertStreamToString(stream);

    mProgressAdmin.addPhotoUploadProgress(photo.length());

    Log.i(TAG, "Uploaded photo " + responseText);
}

From source file:sk.datalan.solr.impl.HttpSolrServer.java

protected HttpRequestBase createMethod(final SolrRequest request) throws IOException, SolrServerException {
    HttpRequestBase method = null;/*from ww w .  j a  v a  2 s .  c o  m*/
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }

    int tries = maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = baseUrl + path;
                    boolean hasNullStreamName = false;
                    if (streams != null) {
                        for (ContentStream cs : streams) {
                            if (cs.getName() == null) {
                                hasNullStreamName = true;
                                break;
                            }
                        }
                    }
                    boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1))
                            && !hasNullStreamName;

                    // only send this list of params as query string params
                    ModifiableSolrParams queryParams = new ModifiableSolrParams();
                    for (String param : this.queryParams) {
                        String[] value = wparams.getParams(param);
                        if (value != null) {
                            for (String v : value) {
                                queryParams.add(param, v);
                            }
                            wparams.remove(param);
                        }
                    }

                    LinkedList<NameValuePair> postParams = new LinkedList<>();
                    if (streams == null || isMultipart) {
                        HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false));
                        post.setHeader("Content-Charset", "UTF-8");
                        if (!isMultipart) {
                            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<FormBodyPart> parts = new LinkedList<>();
                        Iterator<String> iter = wparams.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = wparams.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (isMultipart) {
                                        parts.add(
                                                new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                                    } else {
                                        postParams.add(new BasicNameValuePair(p, v));
                                    }
                                }
                            }
                        }

                        if (isMultipart && streams != null) {
                            for (ContentStream content : streams) {
                                String contentType = content.getContentType();
                                if (contentType == null) {
                                    contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
                                }
                                String name = content.getName();
                                if (name == null) {
                                    name = "";
                                }
                                parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(),
                                        contentType, content.getName())));
                            }
                        }

                        if (parts.size() > 0) {
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                            for (FormBodyPart p : parts) {
                                entity.addPart(p);
                            }
                            post.setEntity(entity);
                        } else {
                            //not using multipart
                            post.setEntity(new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8));
                        }

                        method = post;
                    } // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(wparams, false);
                        HttpPost post = new HttpPost(url + pstr);

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }

                            });
                        } else {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }
                            });
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if (tries < 1) {
                    throw r;
                }
            }
        }
    } catch (IOException ex) {
        throw new SolrServerException("error reading streams", ex);
    }

    return method;
}

From source file:org.apache.camel.component.cxf.jaxrs.simplebinding.CxfRsConsumerSimpleBindingTest.java

@Test
public void testMultipartPostWithoutParameters() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT_PATH + "/rest/customerservice/customers/multipart");
    MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.STRICT);
    multipart.addPart("part1", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    multipart.addPart("part2", new FileBody(
            new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()), "java.jpg"));
    StringWriter sw = new StringWriter();
    jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
    multipart.addPart("body", new StringBody(sw.toString(), "text/xml", Charset.forName("UTF-8")));
    post.setEntity(multipart);//from  ww w .  j a va 2s.com
    HttpResponse response = httpclient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;// w  w  w.j  a v  a 2  s.  co m
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            // CHECK RESPONSE FOR SUCCESS!!
            if (!failed && response != null
                    && response.matches(res.getString(R.string.video_bin_API_good_re))) {
                // We got back HTTP response with valid URL
                Log.d(TAG, " video bin got back URL " + response);

            } else {
                Log.d(TAG, " video bin got eror back:\n" + response);
                failed = true;
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);

                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB);

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(true);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}