Example usage for org.apache.http.entity.mime.content StringBody StringBody

List of usage examples for org.apache.http.entity.mime.content StringBody StringBody

Introduction

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

Prototype

public StringBody(final String text) throws UnsupportedEncodingException 

Source Link

Usage

From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java

@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type Other And"
        + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPISupportToFile")
public void testAddDocumentToAnAPIOtherFile() throws Exception {

    String fileNameAPIM629 = "APIM629.txt";
    String docName = "APIM629PublisherTestHowTo-File-summary";
    String docType = "Other";
    String sourceType = "file";
    String newType = "Type APIM629";
    String summary = "Testing";
    String mimeType = "text/plain";
    String docUrl = "http://";
    String filePathAPIM629 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts"
            + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM629;
    String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag";

    //Send Http Post request to add a new file
    HttpPost httppost = new HttpPost(addDocUrl);
    File file = new File(filePathAPIM629);
    FileBody fileBody = new FileBody(file, "text/plain");

    //Create multipart entity to upload file as multipart file
    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("docLocation", fileBody);
    multipartEntity.addPart("mode", new StringBody(""));
    multipartEntity.addPart("docName", new StringBody(docName));
    multipartEntity.addPart("docUrl", new StringBody(docUrl));
    multipartEntity.addPart("sourceType", new StringBody(sourceType));
    multipartEntity.addPart("summary", new StringBody(summary));
    multipartEntity.addPart("docType", new StringBody(docType));
    multipartEntity.addPart("version", new StringBody(apiVersion));
    multipartEntity.addPart("apiName", new StringBody(apiName));
    multipartEntity.addPart("action", new StringBody("addDocumentation"));
    multipartEntity.addPart("provider", new StringBody(apiProvider));
    multipartEntity.addPart("mimeType", new StringBody(mimeType));
    multipartEntity.addPart("newType", new StringBody(newType));
    multipartEntity.addPart("optionsRadios", new StringBody(docType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));

    httppost.setEntity(multipartEntity);

    //Upload created file and validate
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity));
    assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API ");
}

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 ava2  s  .c  o 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:com.starclub.enrique.BuyActivity.java

public void updateCredit(int credit) {

    progress = new ProgressDialog(this);
    progress.setCancelable(false);/*from w  w w  .j  a va  2  s. com*/
    progress.setMessage("Updating...");

    progress.show();

    m_nCredit = credit;

    new Thread() {
        public void run() {

            HttpParams myParams = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(myParams, 30000);
            HttpConnectionParams.setSoTimeout(myParams, 30000);

            DefaultHttpClient hc = new DefaultHttpClient(myParams);
            ResponseHandler<String> res = new BasicResponseHandler();

            String url = Utils.getUpdateUrl();
            HttpPost postMethod = new HttpPost(url);

            String responseBody = "";
            try {
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                reqEntity.addPart("cid", new StringBody("" + MyConstants.CID));
                reqEntity.addPart("token", new StringBody("" + Utils.getUserToken()));
                reqEntity.addPart("user_id", new StringBody("" + Utils.getUserID()));

                reqEntity.addPart("credit", new StringBody("" + m_nCredit));

                postMethod.setEntity(reqEntity);
                responseBody = hc.execute(postMethod, res);

                System.out.println("update result = " + responseBody);
                JSONObject result = new JSONObject(responseBody);
                if (result != null) {
                    boolean status = result.optBoolean("status");
                    if (status) {

                        m_handler.sendEmptyMessage(1);

                        return;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
            }

            m_handler.sendEmptyMessage(-1);
        }
    }.start();
}

From source file:com.parworks.androidlibrary.ar.ARSiteImpl.java

private MultipartEntity getEntityFromVertices(List<Vertex> vertices) {
    MultipartEntity entity = new MultipartEntity();

    for (Vertex currentVertex : vertices) {
        try {/* w  w w. j  av  a 2 s  . c  o  m*/
            entity.addPart("v",
                    new StringBody((int) currentVertex.getxCoord() + "," + (int) currentVertex.getyCoord()));
        } catch (UnsupportedEncodingException e) {
            throw new ARException(e);
        }
    }
    return entity;
}

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

/**
 * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing 
 * this track to the public./*from   www .  j a  v a  2 s  .  co  m*/
 * 
 * @param fileUri
 * @param contentType
 */
private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) {
    String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, "");
    String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, "");
    String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY,
            "trackable");
    File gpxFile = new File(fileUri.getEncodedPath());
    String hostname = getString(R.string.osm_post_host);
    Integer port = new Integer(getString(R.string.osm_post_port));
    HttpHost targetHost = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    String responseText = "";
    int statusCode = 0;
    Cursor metaData = null;
    String sources = null;
    try {
        metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"),
                new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ",
                new String[] { Constants.DATASOURCES_KEY }, null);
        if (metaData.moveToFirst()) {
            sources = metaData.getString(0);
        }
        if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) {
            throw new IOException("Unable to upload track with materials derived from Google Maps.");
        }

        // The POST to the create node
        HttpPost method = new HttpPost(getString(R.string.osm_post_context));

        // Preemptive basic auth on the first request 
        method.addHeader(
                new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method));

        // Build the multipart body with the upload data
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new FileBody(gpxFile));
        entity.addPart("description", new StringBody(queryForTrackName()));
        entity.addPart("tags", new StringBody(queryForNotes()));
        entity.addPart("visibility", new StringBody(visibility));
        method.setEntity(entity);

        // Execute the POST to OpenStreetMap
        response = httpclient.execute(targetHost, method);

        // Read the response
        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        responseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } catch (AuthenticationException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } finally {
        if (metaData != null) {
            metaData.close();
        }
    }

    if (statusCode == 200) {
        Log.i(TAG, responseText);
        CharSequence text = getString(R.string.osm_success) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText);
        CharSequence text = getString(R.string.osm_failed) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java

private JobInfo send(final File metadataFile, final BinaryData binaryData, final Collection<File> studyFiles,
        final StudyQueryInfo studyQueryInfo) throws IOException, SAXException {
    final HttpPost httpPost = new HttpPost(studyQueryInfo == null ? createURI : updateURI);
    final MultipartEntity entity = new MultipartEntity();

    if (studyQueryInfo != null) {
        entity.addPart(HttpMessagePart.STUDY_UUID.toString(), new StringBody(studyQueryInfo.studyUUID));
    }/* ww  w  .  j a va 2 s .  c om*/

    final StudyMetadata study = useXMLNotGPB ? StudyIO.parseFromXML(metadataFile)
            : StudyIO.parseFromGPB(metadataFile);
    if (studyQueryInfo != null) {
        //Specify current study version
        entity.addPart(HttpMessagePart.OLD_VERSION.toString(), new StringBody(studyQueryInfo.studyVersion));
    }

    //Pretty significant in-memory operations, so scoping to get references released ASAP
    {
        final byte[] metaInBuffer;
        {
            final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(10000);
            if (useXMLNotGPB) {
                StudyIO.writeToXML(study, metaOut);
            } else {
                StudyIO.writeToGPB(study, metaOut);
            }
            metaInBuffer = metaOut.toByteArray();
        }
        final ByteArrayInputStream metaIn = new ByteArrayInputStream(metaInBuffer);
        //We must distinguish MIME types for GPB vs. XML so that the server can handle them properly
        entity.addPart(metadataFile.getName(), new InputStreamBody(metaIn,
                useXMLNotGPB ? "text/xml" : "application/octet-stream", metadataFile.getName()));
    }

    //We support only one type
    assert binaryData instanceof BinaryDcmData;
    {
        int i = 0;
        for (final InputStream binaryStream : iter(((BinaryDcmData) binaryData).streamIterator())) {
            final String fileName = "binary" + i++;
            entity.addPart(fileName, new InputStreamBody(binaryStream, fileName));
        }
    }

    //Debugging only
    //        int i = 0;
    //        for (final InputStream binaryStream: Iter.iter(((BinaryDcmData) binaryData).streamIterator())) {
    //            final OutputStream testout = new BufferedOutputStream(new FileOutputStream("E:/testdata/" + i), 10000);
    //            for(;;) {
    //                final int val = binaryStream.read();
    //                if (val == -1) {
    //                    break;
    //                }
    //                testout.write(val);
    //            }
    //            testout.close();
    //            ++i;
    //        }

    httpPost.setEntity(entity);

    final String response = httpClient.execute(httpPost, new BasicResponseHandler());
    final long uploadEndTime = System.currentTimeMillis();

    LOG.debug("Server response:" + response);

    final String jobID;
    final String studyID;
    final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes()));
    try {
        jobID = xPath.evaluate("/jobStatus/@jobID", responseDoc).trim();
        studyID = xPath.evaluate("/jobStatus/@studyUUID", responseDoc).trim();
    } catch (final XPathExpressionException e) {
        //This shouldn't happen
        throw new RuntimeException(e);
    }
    final JobInfo jobInfo = new JobInfo(jobID, studyID, studyFiles, uploadEndTime);
    jobIDInfo.put(jobID, jobInfo);
    return jobInfo;
}

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  ww w  .  j a va2 s .  c  o m
    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:org.ow2.proactive_grid_cloud_portal.scheduler.server.SchedulerServiceImpl.java

private MultipartEntity createLoginPasswordSSHKeyMultipart(String login, String pass, String ssh)
        throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("username", new StringBody(login));
    entity.addPart("password", new StringBody(pass));

    if (ssh != null && !ssh.isEmpty()) {
        entity.addPart("sshKey", new ByteArrayBody(ssh.getBytes(), MediaType.APPLICATION_OCTET_STREAM, null));
    }// w  w w  . java 2 s. c om

    return entity;
}

From source file:project.cs.lisa.netinf.node.resolution.NameResolutionService.java

/**
 * Creates an HTTP POST representation of a NetInf PUBLISH message.
 * @param io/*from   w  w  w .j  a va2  s.c  om*/
 *     The information object to publish
 * @return
 *     A HttpPost representing the NetInf PUBLISH message
 * @throws UnsupportedEncodingException
 *     In case the encoding is not supported
 */
private HttpPost createPublish(InformationObject io) throws UnsupportedEncodingException {

    Log.d(TAG, "createPublish()");

    // Extracting values from IO's identifier
    String hashAlg = getHashAlg(io.getIdentifier());
    String hash = getHash(io.getIdentifier());
    String contentType = getContentType(io.getIdentifier());
    String meta = getMetadata(io.getIdentifier());
    String bluetoothMac = getBluetoothMac(io);
    String filePath = getFilePath(io);

    HttpPost post = new HttpPost(mHost + ":" + mPort + "/netinfproto/publish");

    MultipartEntity entity = new MultipartEntity();

    StringBody uri = new StringBody("ni:///" + hashAlg + ";" + hash + "?ct=" + contentType);
    entity.addPart("URI", uri);

    StringBody msgid = new StringBody(Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX)));
    entity.addPart("msgid", msgid);

    if (bluetoothMac != null) {
        StringBody l = new StringBody(bluetoothMac);
        entity.addPart("loc1", l);
    }

    if (meta != null) {
        StringBody ext = new StringBody(meta.toString());
        entity.addPart("ext", ext);
    }

    if (filePath != null) {
        StringBody fullPut = new StringBody("true");
        entity.addPart("fullPut", fullPut);
        FileBody octets = new FileBody(new File(filePath));
        entity.addPart("octets", octets);
    }

    StringBody rform = new StringBody("json");
    entity.addPart("rform", rform);

    try {
        entity.writeTo(System.out);
    } catch (IOException e) {
        Log.e(TAG, "Failed to write MultipartEntity to System.out");
    }

    post.setEntity(entity);
    return post;
}