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() 

Source Link

Usage

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);/*from ww  w.j a v  a2s. co  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:holon.util.HTTP.java

public static Payload form(Map<String, Object> fields) {
    return () -> {
        MultipartEntity entity = new MultipartEntity();
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (entry.getValue() instanceof File) {
                entity.addPart(entry.getKey(), new FileBody((File) entry.getValue()));
            } else {
                try {
                    entity.addPart(entry.getKey(), new StringBody((String) entry.getValue()));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }//  w  ww  .j  a  v  a 2 s  . c  o m
            }
        }
        return entity;
    };
}

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

@Override
public BodhiLoginResponse login(String username, String password) throws BodhiClientLoginException {
    BodhiLoginResponse result = null;//from   w  ww  .j a va  2s. 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:com.captchatrader.CaptchaTrader.java

/**
 * Responds if an CAPTCHA wes correctly answered or not
 * //  w  w w . j  a  v a 2 s . co  m
 * @param captcha
 *            the CAPTCHA object
 * @param state
 *            <code>true</code> if the CAPTCHA was correctly resolved
 * @throws CaptchaTraderException
 *             any of the possible errors
 */
public void respond(ResolvedCaptcha captcha, boolean state) throws CaptchaTraderException, IOException {
    final URI requestUri = apiURI.resolve("respond");
    final HttpPost request = new HttpPost(requestUri);
    final MultipartEntity entity = new MultipartEntity();

    entity.addPart("is_correct", new StringBody(state ? "1" : "0"));
    entity.addPart("password", new StringBody(password));
    entity.addPart("ticket", new StringBody(captcha.getID()));
    entity.addPart("username", new StringBody(username));

    request.setEntity(entity);
    validate(execute(request));
}

From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java

protected String getData(URI location) throws APIException {
    Log.d("HTTPAPIRequest", "Downloading " + location);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(location);
    client.addRequestInterceptor(preemptiveAuth, 0);

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    if (!m_params.isEmpty()) {
        MultipartEntity params = new MultipartEntity();
        for (Entry<String, Object> item : m_params.entrySet()) {
            Object value = item.getValue();
            ContentBody data;//from www  .  j av a  2s.  c  o  m
            if (value instanceof Attachment) {
                Attachment attachment = (Attachment) value;
                try {
                    data = new InputStreamBody(attachment.getStream(), attachment.contentType(),
                            attachment.name());
                    Log.d("HTTPAPIRequest",
                            "Found a " + attachment.contentType() + " attachment named " + attachment.name());
                } catch (FileNotFoundException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                } catch (IOException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                }
            } else {
                try {
                    data = new StringBody(value.toString());
                } catch (UnsupportedEncodingException e) {
                    getRequest().setError(ErrorType.ERROR_INTERNAL);
                    throw new APIException();
                }
            }
            params.addPart(item.getKey(), data);
        }
        post.setEntity(params);
    }

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(),
            m_api.getAccount().getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    HttpResponse req;
    try {
        req = client.execute(post);
    } catch (ClientProtocolException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    } catch (IOException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED);
        throw new APIException();
    }

    InputStream result;
    try {
        result = req.getEntity().getContent();
    } catch (IllegalStateException e1) {
        getRequest().setError(ErrorType.ERROR_INTERNAL);
        throw new APIException();
    } catch (IOException e1) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }

    InputStreamReader in = null;
    int status;
    in = new InputStreamReader(result);
    status = req.getStatusLine().getStatusCode();
    Log.d("HTTPAPIRequest", "Got status code of " + status);
    setStatusCode(status);
    if (status >= 300 || status < 200) {
        getRequest().setError(ErrorType.ERROR_SERVER);
        Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status);
        throw new APIException();
    }

    int totalSize = -1;
    if (req.containsHeader("Content-length"))
        totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue());

    char[] buffer = new char[1024];
    //2^17 = 131072.
    StringBuilder contents = new StringBuilder(131072);
    try {
        int size = 0;
        while ((totalSize > 0 && size < totalSize) || totalSize == -1) {
            int readSize = in.read(buffer);
            size += readSize;
            if (readSize == -1)
                break;
            if (totalSize >= 0)
                getRequest().publishProgress(new APIProgress((size / totalSize) * 5000));
            contents.append(buffer, 0, readSize);
        }
    } catch (IOException e) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }
    return contents.toString();
}

From source file:org.openml.knime.OpenMLWebservice.java

/**
 * Upload an implementation.//from w w w .j  a  v  a  2  s  .  c o m
 * 
 * 
 * @param description Implementation description file
 * @param workflow Workflow file
 * @param user Name of the user
 * @param password Password of the user
 * @return Response from the server
 * @throws Exception If communication failed
 */
public static String sendImplementation(final File description, final File workflow, final String user,
        final String password) throws Exception {
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80);
        httpclient.getCredentialsProvider().setCredentials(scope, credentials);
        String url = WEBSERVICEURL + "?f=openml.implementation.upload";
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
        FileBody descBin = new FileBody(description);
        reqEntity.addPart("description", descBin);
        FileBody workflowBin = new FileBody(workflow);
        reqEntity.addPart("source", workflowBin);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() < 200) {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        if (resEntity != null) {
            result = convertStreamToString(resEntity.getContent());
        }
        ErrorDocument errorDoc = null;
        try {
            errorDoc = ErrorDocument.Factory.parse(result);
        } catch (Exception e) {
            // no error XML should mean no error
        }
        if (errorDoc != null && errorDoc.validate()) {
            ErrorDocument.Error error = errorDoc.getError();
            String errorMessage = error.getCode() + " : " + error.getMessage();
            if (error.isSetAdditionalInformation()) {
                errorMessage += " : " + error.getAdditionalInformation();
            }
            throw new Exception(errorMessage);
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
            // ignore
        }
    }
    return result;
}

From source file:com.wialon.remote.ApacheSdkHttpClient.java

@Override
public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) {
    try {/*from ww  w .  ja va2 s .  com*/
        HttpPost httpPost = new HttpPost(url);
        MultipartEntity multipartEntity = new MultipartEntity();
        if (params != null)
            for (Map.Entry<String, String> entry : params.entrySet())
                multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
        multipartEntity.addPart("file", new FileBody(file));
        httpPost.setEntity(multipartEntity);
        sendRequest(getHttpClient(timeout), httpPost, callback);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        callback.error = e;
        callback.done(null);
    }
}