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:sjizl.com.FileUploadTest.java

private void doFileUpload(String path) {

    String username = "";
    String password = "";
    String foto = "";
    String foto_num = "";
    SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
    username = sp.getString("username", null);
    password = sp.getString("password", null);
    foto = sp.getString("foto", null);
    foto_num = sp.getString("foto_num", null);

    File file1 = new File(path);

    String urlString = "http://sjizl.com/postBD/UploadToServer.php?username=" + username + "&password="
            + password;/*from  w w  w. jav  a 2s .  c om*/
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlString);
        FileBody bin1 = new FileBody(file1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploadedfile1", bin1);

        reqEntity.addPart("user", new StringBody("User"));
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);
        if (resEntity != null) {
            Log.i("RESPONSE", response_str);
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        // res.setTextColor(Color.GREEN);
                        // res.setText("n Response from server : n " + response_str);

                        CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this,
                                "Upload Complete! ", null, R.drawable.iconbd);

                        Brows();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    } catch (Exception ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }

    //RegisterActivity.login(username,password,getApplicationContext());

}

From source file:com.makotosan.vimeodroid.vimeo.Methods.java

public void uploadFile(String endpoint, String ticketId, File file, String filename, ProgressListener listener,
        OnTransferringHandler handler) throws OAuthMessageSignerException, OAuthExpectationFailedException,
        OAuthCommunicationException, ClientProtocolException, IOException {
    // final int chunkSize = 512 * 1024; // 512 kB
    // final long pieces = file.length() / chunkSize;
    int chunkId = 0;

    final HttpPost request = new HttpPost(endpoint);

    // BufferedInputStream stream = new BufferedInputStream(new
    // FileInputStream(file));

    // for (chunkId = 0; chunkId < pieces; chunkId++) {
    // byte[] buffer = new byte[chunkSize];

    // stream.skip(chunkId * chunkSize);

    // stream.read(buffer);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("chunk_id", new StringBody(String.valueOf(chunkId)));
    entity.addPart("ticket_id", new StringBody(ticketId));
    request.setEntity(new CountingRequestEntity(entity, listener)); // ,
    // chunkId/*from   ww  w .  j av  a 2 s . co m*/
    // *
    // chunkSize));
    // ByteArrayInputStream arrayStream = new ByteArrayInputStream(buffer);

    Authentication.signRequest(getConsumerInfo(), request);

    entity.addPart("file_data", new FileBody(file));
    // entity.addPart("file_data", new InputStreamBody(arrayStream,
    // filename));

    final HttpClient client = app.getHttpClient();

    handler.onTransferring(request);
    final HttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
        responseEntity.consumeContent();
    }
    // }
}

From source file:org.overlord.sramp.governance.workflow.Multipart.java

public void post(HttpClient httpclient, URI uri, Map<String, Object> parameters)
        throws IOException, WorkflowException {
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (String key : parameters.keySet()) {
        ContentBody content = null;//from   w  ww  .  j a v  a  2s.  c om
        Object param = parameters.get(key);
        if (param instanceof String) {
            StringBody stringBody = new StringBody((String) param, "text/plain", Charset.forName("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
            content = stringBody;
        } else {
            //turn object into byteArray, or it also supports InputStreamBody or FileBody
            ByteArrayBody byteBody = new ByteArrayBody(null, key);
            content = byteBody;
        }
        multiPartEntity.addPart(key, content);
    }
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(multiPartEntity);
    HttpResponse response = httpclient.execute(httpPost);
    InputStream is = response.getEntity().getContent();
    String responseStr = IOUtils.toString(is);
    if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) {
        logger.debug(responseStr);
    } else {
        throw new WorkflowException(
                "Workflow ERROR - HTTP STATUS CODE " + response.getStatusLine().getStatusCode() + ". " //$NON-NLS-1$ //$NON-NLS-2$
                        + response.getStatusLine().getReasonPhrase() + ". " + responseStr); //$NON-NLS-1$
    }
    is.close();
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
private void doMultipart(HttpPost method, HttpServletRequest req)
        throws ServletException, FileUploadException, UnsupportedEncodingException, IOException {
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(TEMP_DIR);

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

    List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req);

    MultipartEntity entity = new MultipartEntity();

    for (FileItem fItem : fileItems) {
        if (fItem.isFormField()) {
            LOG.log(Level.INFO, "Form field {0}", fItem.getName());

            StringBody part = new StringBody(fItem.getFieldName());
            entity.addPart(fItem.getFieldName(), part);
        } else {//from  w  w  w . j a v  a  2s. co m
            LOG.log(Level.INFO, "File item {0}", fItem.getName());

            InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(),
                    fItem.getContentType());
            entity.addPart(fItem.getFieldName(), file);
        }
    }

    method.setEntity(entity);
}

From source file:ca.mcgill.hs.serv.LogFileUploaderService.java

/**
 * Uploads the specified file to the server.
 * //w w w . j a v a 2 s. c  om
 * @param fileName
 *            The file to upload
 * @return A code indicating the result of the upload.
 */
private int uploadFile(final String fileName) {
    Log.d(TAG, "Uploading " + fileName);
    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    httppost = new HttpPost(UPLOAD_URL);
    final File file = new File(HSAndroid.getStorageDirectory(), fileName);
    if (!file.exists()) {
        // File may be deleted while in the queue for uploading
        Log.d(TAG, "Unable to upload " + fileName + ". File does not exist.");
        return UPLOAD_FAILED_FILE_NOT_FOUND_ERROR_CODE;
    }
    Log.d(TAG, "MAC ADDRESS: " + wifiInfo.getMacAddress());
    httppost.addHeader("MAC", wifiInfo.getMacAddress());

    final MultipartEntity mpEntity = new MultipartEntity();
    final ContentBody cbFile = new FileBody(file, "binary/octet-stream");
    mpEntity.addPart("uploadedfile", cbFile);

    httppost.setEntity(mpEntity);
    try {
        final HttpResponse response = httpclient.execute(httppost);
        final HttpEntity resEntity = response.getEntity();

        String responseMsg = "";
        if (resEntity != null) {
            responseMsg = EntityUtils.toString(resEntity);
            resEntity.consumeContent();
        }
        Log.i(TAG, "Server Response: " + responseMsg);
        if (responseMsg.contains("FAILURE")) {
            CURRENT_ERROR_CODE = UPLOAD_FAILED_ERROR_CODE;
            return UPLOAD_FAILED_ERROR_CODE;
        }
        // Move files to uploaded folder if successful
        else {
            Log.i(TAG, "Moving file to uploaded directory.");
            final File dest = new File(HSAndroid.getStorageDirectory(),
                    HSAndroid.getAppString(R.string.uploaded_file_path));
            if (!dest.isDirectory()) {
                if (!dest.mkdirs()) {
                    throw new IOException("ERROR: Unable to create directory " + dest.getName());
                }
            }

            if (!file.renameTo(new File(dest, file.getName()))) {
                throw new IOException("ERROR: Unable to transfer file " + file.getName());
            }
        }

    } catch (final MalformedURLException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = MALFORMEDURLEXCEPTION_ERROR_CODE;
        return MALFORMEDURLEXCEPTION_ERROR_CODE;
    } catch (final UnknownHostException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = UNKNOWNHOSTEXCEPTION_ERROR_CODE;
        return UNKNOWNHOSTEXCEPTION_ERROR_CODE;
    } catch (final IOException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = IOEXCEPTION_ERROR_CODE;
        return IOEXCEPTION_ERROR_CODE;
    } catch (final IllegalStateException e) {
        Log.e(TAG, android.util.Log.getStackTraceString(e));
        CURRENT_ERROR_CODE = ILLEGALSTATEEXCEPTION_ERROR_CODE;
        return ILLEGALSTATEEXCEPTION_ERROR_CODE;
    }
    return NO_ERROR_CODE;
}

From source file:com.phodev.http.tools.RequestEntity.java

/**
 * POST// w w w  .ja  v  a  2 s  . com
 * 
 * <pre>
 * RequestMethod{@link ConnectionHelper.RequestMethod#POST_WITH_FILE}}?
 * </pre>
 * 
 * @param postValues
 * @param files
 * @param charset
 */
public RequestEntity setPostEntitiy(List<NameValuePair> postValues, String charset, Map<String, File> files) {
    Charset c = null;
    try {
        c = Charset.forName(charset);
        Charset.defaultCharset();
    } catch (Exception e) {
        c = null;
    }
    MultipartEntity entity;
    HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE;
    if (c == null) {
        entity = new MultipartEntity(mode);
    } else {
        entity = new MultipartEntity(mode, null, c);
    }
    postEntity = entity;
    if (postValues != null) {
        for (NameValuePair v : postValues) {
            try {
                entity.addPart(v.getName(), new StringBody(v.getValue()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    if (files != null) {
        Iterator<Entry<String, File>> iterator = files.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, File> entry = iterator.next();
            entity.addPart(entry.getKey(), new FileBody(entry.getValue()));
        }
    }
    return this;
}

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

    poster.setEntity(reqEntity);/* w w w  . j  av a  2s .co m*/
    JsonPayload response = performRequest(poster);

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

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

private void sendToJogmap(Uri fileUri, String contentType) {
    String authCode = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.JOGRUNNER_AUTH,
            "");/* w ww  .j  av a  2s.  c  o m*/
    File gpxFile = new File(fileUri.getEncodedPath());
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    URI jogmap = null;
    String jogmapResponseText = "";
    int statusCode = 0;
    try {
        jogmap = new URI(getString(R.string.jogmap_post_url));
        HttpPost method = new HttpPost(jogmap);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("id", new StringBody(authCode));
        entity.addPart("mFile", new FileBody(gpxFile));
        method.setEntity(entity);
        response = httpclient.execute(method);

        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        jogmapResponseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + jogmap.toString(), e);
        CharSequence text = getString(R.string.jogmap_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } catch (URISyntaxException e) {
        //Log.e(TAG, "Failed to use configured URI " + jogmap.toString(), e);
        CharSequence text = getString(R.string.jogmap_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
    if (statusCode == 200) {
        CharSequence text = getString(R.string.jogmap_success) + jogmapResponseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Wrong status code " + statusCode);
        CharSequence text = getString(R.string.jogmap_failed) + jogmapResponseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:ecblast.test.EcblastTest.java

public String compareReactions(String queryFormat, String query, String targetFormat, String target)
        throws Exception {
    DefaultHttpClient client;/*from   w  w w.j a  v a  2 s .c om*/
    client = new DefaultHttpClient();
    String urlString = "http://localhost:8080/ecblast-rest/compare";
    HttpPost postRequest = new HttpPost(urlString);
    try {
        //Set various attributes
        MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : ""));
        //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName()));
        switch (queryFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(query));
            //Prepare payload
            multiPartEntity.addPart("q", fileBody);
            multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("q", new StringBody(query, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("Q", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }
        switch (targetFormat) {
        case "RXN":
            FileBody fileBody = new FileBody(new File(target));
            //Prepare payload
            multiPartEntity.addPart("t", fileBody);
            multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8")));
            break;
        case "SMI":
            multiPartEntity.addPart("t", new StringBody(target, "text/plain", Charset.forName("UTF-8")));
            multiPartEntity.addPart("T", new StringBody("SMI", "text/plain", Charset.forName("UTF-8")));
            break;
        }

        //Set to request body
        postRequest.setEntity(multiPartEntity);

        //Send request
        HttpResponse response = client.execute(postRequest);

        //Verify response if any
        if (response != null) {
            System.out.println(response.getStatusLine().getStatusCode());
            return response.toString();
        }
    } catch (IOException ex) {
    }
    return null;
}

From source file:ro.teodorbaciu.commons.client.ws.BaseWsMethods.java

/**
 * Handles the communication details with the server.
 * /* w w  w.  j a va 2  s.co m*/
 * @param moduleName the name of the module
 * @param op the operation to call
 * @param targetUrl the url to post the call
 * @param wsParamsList contains the parameters to submit for the webservice call
 * @return the result of the call
 * @throws Exception if an error occurs
 */
private String callServerMultipartPost(String moduleName, String op, String targetUrl,
        List<NameValuePair> wsParamsList, File fileToUpload, WriteListener writeListener)
        throws AuthorizationRequiredException, OperationForbiddenException, UnsupportedEncodingException,
        ClientProtocolException, IOException {

    if (currentRequest != null) {
        throw new RuntimeException("Another webservice request is still executing !");
    }

    MultipartEntity reqEntity = null;
    if (writeListener != null) {
        reqEntity = new MultipartEntityWithProgressMonitoring(writeListener);
    } else {
        reqEntity = new MultipartEntity();
    }

    for (NameValuePair pair : wsParamsList) {
        reqEntity.addPart(pair.getName(), new StringBody(pair.getValue()));
    }
    reqEntity.addPart("data", new FileBody(fileToUpload));

    String postUrl = targetUrl + "?module=" + moduleName + "&op=" + op;
    HttpPost post = new HttpPost(postUrl);
    post.setEntity(reqEntity);

    return processServerPost(post);
}