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:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

/**
 * Login to Bungeni via the OAuth route//from  ww w  .j  a  v a 2s. c o  m
 * @param oauthForwardURL
 * @param oauthCameFromURL
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
private String oauthAuthenticate(String oauthForwardURL, String oauthCameFromURL)
        throws UnsupportedEncodingException, IOException {

    final HttpPost post = new HttpPost(oauthForwardURL);
    final HashMap<String, ContentBody> nameValuePairs = new HashMap<String, ContentBody>();
    nameValuePairs.put("login", new StringBody(this.getUser()));
    nameValuePairs.put("password", new StringBody(this.getPassword()));
    nameValuePairs.put("camefrom", new StringBody(oauthCameFromURL));
    nameValuePairs.put("actions.login", new StringBody("login"));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }
    HttpContext context = new BasicHttpContext();
    post.setEntity(entity);
    HttpResponse oauthResponse = client.execute(post, context);
    // if the OAuth page retrieval failed throw an exception
    if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(oauthResponse.getStatusLine().toString());
    }
    String currentUrl = getRequestEndContextURL(context);
    // consume the response
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(oauthResponse);
    consumeContent(oauthResponse.getEntity());
    return currentUrl;
}

From source file:org.coronastreet.gpxconverter.GarminForm.java

public void upload() {
    httpClient = HttpClientBuilder.create().build();
    localContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    if (doLogin()) {
        try {//from  ww w  .  j a v a2s . co  m
            HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#");
            HttpResponse formResponse = httpClient.execute(get, localContext);
            HttpEntity formEntity = formResponse.getEntity();
            EntityUtils.consume(formEntity);

            HttpPost request = new HttpPost(
                    "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx");
            request.setHeader("Referer",
                    "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1");
            request.setHeader("Accept", "text/html, application/xhtml+xml, */*");
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("data",
                    new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx"));

            // Need to do this bit because without it you can't disable chunked encoding
            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            entity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

            bArrEntity.setChunked(false);
            bArrEntity.setContentEncoding(entity.getContentEncoding());
            bArrEntity.setContentType(entity.getContentType());

            request.setEntity(bArrEntity);

            HttpResponse response = httpClient.execute(request, localContext);

            if (response.getStatusLine().getStatusCode() != 200) {
                log("Failed to Upload");
                HttpEntity en = response.getEntity();
                if (en != null) {
                    String output = EntityUtils.toString(en);
                    log(output);
                }
            } else {
                HttpEntity ent = response.getEntity();
                if (ent != null) {
                    String output = EntityUtils.toString(ent);
                    output = "[" + output + "]"; //OMG Garmin Sucks at JSON.....
                    JSONObject uploadResponse = new JSONArray(output).getJSONObject(0);
                    JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult");
                    try {
                        int uploadID = importResult.getInt("uploadId");
                        log("Success! UploadID is " + uploadID);
                    } catch (Exception e) {
                        JSONArray failures = (JSONArray) importResult.get("failures");
                        JSONObject failure = (JSONObject) failures.get(0);
                        JSONArray errorMessages = failure.getJSONArray("messages");
                        JSONObject errorMessage = errorMessages.getJSONObject(0);
                        String content = errorMessage.getString("content");
                        log("Upload Failed! Error: " + content);
                    }
                }
            }
            httpClient.close();
        } catch (Exception ex) {
            log("Exception? " + ex.getMessage());
            ex.printStackTrace();
            // handle exception here
        }
    } else {
        log("Failed to upload!");
    }
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

/**
 * Issue a POST against the API.//  w  w w .  j a  v  a2 s .  c o  m
 * 
 * @param path The web service endpoint
 * @param o The object to POST. This object will be serialized into XML
 *        prior to being sent.
 * @param responseHandler
 *            The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response.
 * @return The response object from the operation. This response will be of
 *         the type given in the responseHandler argument.
 * @throws IOException If a network error occurs during the request.
 */
public <T> T doPost(String path, Object o, ResponseHandler<T> responseHandler) throws IOException {
    HttpPost post = new HttpPost();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        XmlUtil.serialize(o, bos, Boolean.FALSE);
    } catch (JAXBException e) {
        ServiceError error = new ServiceError();

        error.setErrorCode("UnexpectedError");
        error.setReasonText("Unable to serialize response");

        if (_log.isDebugEnabled()) {
            _log.debug("Unable to serialize response", e);
        }

        return responseHandler.getErrorResponse(error);
    }

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    multipartEntity.addPart("postdata", new StringBody(bos.toString("UTF-8"), Charset.forName("UTF-8")));
    post.setEntity(multipartEntity);

    return runMethod(post, path, responseHandler);
}

From source file:com.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox./*from  w  w w .  j a v  a2 s .  c om*/
 */
public HttpResponse putFileStream(String root, String to_path, String name, InputStream stream, long length)
        throws DropboxException {
    String path = "/files/" + root + to_path;

    HttpClient client = getClient();

    try {
        String target = buildFullURL(secureProtocol, content_host, this.port,
                buildURL(path, API_VERSION, null));
        HttpPost req = new HttpPost(target);
        // this has to be done this way because of how oauth signs params
        // first we add a "fake" param of file=path of *uploaded* file
        // THEN we sign that.
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("file", name));
        req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        consumer.sign(req);

        // now we can add the real file multipart and we're good
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileStreamBody bin = new FileStreamBody(stream, name, length);
        entity.addPart("file", bin);
        // this resets it to the new entity with the real file
        req.setEntity(entity);

        HttpResponse resp = client.execute(req);

        resp.getEntity().consumeContent();
        return resp;
    } catch (Exception e) {
        throw new DropboxException(e);
    }
}

From source file:com.fhc25.percepcion.osiris.mapviewer.common.restutils.RestClient.java

/**
 * Executes the requests.//ww w  . j  a va2  s .  co m
 *
 * @param method   the type of method (POST, GET, DELETE, PUT).
 * @param url      the url of the request.
 * @param headers  the headers to include.
 * @param listener a listener for callbacks.
 * @throws Exception
 */
public static void Execute(final File file, final RequestMethod method, final String url,
        final ArrayList<NameValuePair> headers, final RestListener listener) throws Exception {
    new Thread() {
        @Override
        public void run() {

            switch (method) {
            case GET:
                // Do nothing
                break;

            case POST: {

                HttpPost request = new HttpPost(url);
                // add headers
                if (headers != null) {
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }

                // code file
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Log.d(TAG, "UPLOAD: file length = " + file.length());
                Log.d(TAG, "UPLOAD: file exist = " + file.exists());
                FileBody bodyPart = new FileBody(file);
                entity.addPart("file", bodyPart);
                request.setEntity(entity);

                Log.i(TAG, "Request with File:" + request.getEntity());

                executeRequest(request, url, listener);
            }
                break;

            case PUT: {
                HttpPut request = new HttpPut(url);
                // add headers
                if (headers != null) {
                    for (NameValuePair h : headers)
                        request.addHeader(h.getName(), h.getValue());
                }

                // code file
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Log.d(TAG, "UPLOAD: file length = " + file.length());
                Log.d(TAG, "UPLOAD: file exist = " + file.exists());
                FileBody bodyPart = new FileBody(file);
                entity.addPart("file", bodyPart);
                request.setEntity(entity);

                Log.v(TAG, "Request " + request.toString());
                executeRequest(request, url, listener);
            }
                break;

            case DELETE:
                // Do nothing
                break;

            } // switch end
        }
    }.start();
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

private MultipartEntity getMultiPartEntity(HashMap<String, ContentBody> nameValuePairs) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Set<String> fields = nameValuePairs.keySet();
    for (String fieldName : fields) {
        entity.addPart(fieldName, nameValuePairs.get(fieldName));
    }/*from w ww  .j ava  2 s  . c  om*/
    return entity;
}

From source file:de.raptor2101.GalDroid.WebGallery.Gallery3.Gallery3Imp.java

public String getSecurityToken(String user, String password) throws SecurityException {
    try {//w ww  .ja  v  a2s  .  co  m
        HttpPost httpRequest = new HttpPost(LinkRest_LoadSecurityToken);

        httpRequest.addHeader("X-Gallery-Request-Method", "post");
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        mpEntity.addPart("user", new StringBody(user));
        mpEntity.addPart("password", new StringBody(password));

        httpRequest.setEntity(mpEntity);
        HttpResponse response;

        response = mHttpClient.execute(httpRequest);
        InputStream inputStream = response.getEntity().getContent();
        InputStreamReader streamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(streamReader);
        String content = reader.readLine();
        inputStream.close();
        if (content.length() == 0 || content.startsWith("[]")) {
            throw new SecurityException("Couldn't verify user-credentials");
        }

        return content.trim().replace("\"", "");
    } catch (Exception e) {
        throw new SecurityException("Couldn't verify user-credentials", e);
    }
}

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

private String createOpenGpsTrackerBundle() throws OAuthMessageSignerException, OAuthExpectationFailedException,
        OAuthCommunicationException, IOException {
    HttpPost method = new HttpPost("http://api.gobreadcrumbs.com/v1/bundles.xml");
    if (isCancelled()) {
        throw new IOException("Fail to execute request due to canceling");
    }/*w  ww .java 2  s .  c om*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("name", new StringBody(mBundleName));
    entity.addPart("activity_id", new StringBody(mActivityId));
    entity.addPart("description", new StringBody(mBundleDescription));
    method.setEntity(entity);

    mConsumer.sign(method);
    HttpResponse response = mHttpClient.execute(method);
    HttpEntity responseEntity = response.getEntity();
    InputStream stream = responseEntity.getContent();
    String responseText = XmlCreator.convertStreamToString(stream);
    Pattern p = Pattern.compile(">([0-9]+)</id>");
    Matcher m = p.matcher(responseText);
    String bundleId = null;
    if (m.find()) {
        bundleId = m.group(1);

        ContentValues values = new ContentValues();
        values.put(MetaData.KEY, BreadcrumbsTracks.BUNDLE_ID);
        values.put(MetaData.VALUE, bundleId);
        Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata");

        mContext.getContentResolver().insert(metadataUri, values);
        mIsBundleCreated = true;
    } else {
        String text = "Unable to upload (yet) without a bunld id stored in meta-data table";
        IllegalStateException e = new IllegalStateException(text);
        handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text);
    }
    return bundleId;
}

From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java

private boolean uploadFile(final HttpClient client, File file)
        throws IOException, ClientProtocolException, JSONException, UnsupportedEncodingException {
    Log.d(TAG, "uploadFile " + file);

    final HttpPost httpost = new HttpPost(apiUri);

    final MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    populateMultipartEntity(multipartEntity, file);

    httpost.setEntity(multipartEntity);//w  ww . j av  a  2  s.  co m

    final HttpResponse fileUploadResponse = client.execute(httpost);
    final String uploadResult = getRequestContent(fileUploadResponse);

    if (uploadResult == null) {

        showBatchUploadNotification(getString(R.string.batch_upload_failed), 75, false);
        return false;
    }

    final JSONObject root = (JSONObject) new JSONTokener(uploadResult).nextValue();

    if (root.has(UPLOAD_RESULT_MESSAGE)) {
        final String message = root.getInt(UPLOAD_RESULT_CODE) == 200
                ? getString(R.string.batch_upload_successful)
                : getString(R.string.batch_upload_failed);

        showBatchUploadNotification(message, MAX_PROGRESS, false);

        return true;
    }

    return false;
}

From source file:com.su.search.client.solrj.PaHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, final ResponseParser processor)
        throws SolrServerException, IOException {
    HttpRequestBase method = null;/*from   ww w  .ja  va  2 s.c o  m*/
    InputStream is = null;
    SolrParams params = request.getParams();

    // modified by wangqiang406 2012-07-27
    // ??
    if (null != password) {
        ModifiableSolrParams wparams = new ModifiableSolrParams(params);
        wparams.set(SimpleIndexClient.KEY_PA_AUTH, password);
        params = wparams;
    }

    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);
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }
    params = wparams;

    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(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = baseUrl + path;

                    boolean isMultipart = (streams != null && streams.size() > 1);

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

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

                        if (isMultipart) {
                            for (ContentStream content : streams) {
                                parts.add(new FormBodyPart(content.getName(),
                                        new InputStreamBody(content.getStream(), 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
                            HttpEntity e;
                            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(params, 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);
    }

    // TODO: move to a interceptor?
    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    method.addHeader("User-Agent", AGENT);

    InputStream respBody = null;

    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        String charset = EntityUtils.getContentCharSet(response.getEntity());
        respBody = response.getEntity().getContent();

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
            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;
        case HttpStatus.SC_NOT_FOUND:
            throw new SolrServerException("Server at " + getBaseURL() + " was not found (404).");
        default:
            throw new SolrServerException("Server at " + getBaseURL() + " returned non ok status:" + httpStatus
                    + ", message:" + response.getStatusLine().getReasonPhrase());

        }
        NamedList<Object> rsp = processor.processResponse(respBody, charset);
        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 SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), reason);
        }
        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) {
            try {
                respBody.close();
            } catch (Throwable t) {
            } // ignore
        }
    }
}