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:palamarchuk.smartlife.app.RegisterActivity.java

private void startRegisterProcess(String deviceKey) {
    String url = ServerRequest.DOMAIN + "/users";
    MultipartEntity multipartEntity;/*w w  w  .  j a v  a2 s. com*/

    // collect data
    try {
        multipartEntity = collectData();
        multipartEntity.addPart("token", new StringBody(deviceKey));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    QueryMaster queryMaster = new QueryMaster(RegisterActivity.this, url, QueryMaster.QUERY_POST,
            multipartEntity);
    queryMaster.setProgressDialog();

    queryMaster.setOnCompleteListener(new QueryMaster.OnCompleteListener() {
        @Override
        public void complete(String serverResponse) {
            try {
                JSONObject jsonObject = new JSONObject(serverResponse);
                String status = jsonObject.getString("status");

                if (status.equalsIgnoreCase(ServerRequest.STATUS_SUCCESS)) {
                    Toast.makeText(RegisterActivity.this, "??  ?",
                            Toast.LENGTH_SHORT).show();

                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(SHARED_PREF_PHONE, phone.getText().toString());
                    editor.putString(SHARED_PREF_PASSWORD, password.getText().toString());
                    editor.apply();

                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    builder.setMessage(
                            "?      ?? ?,    ");
                    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //                                startLoginActivityAutoStart(RegisterActivity.this);
                            Intent loginActivity = new Intent(RegisterActivity.this, LoginActivity.class);
                            loginActivity.putExtra(LoginActivity.SMS_VERIFICATION, true);
                            loginActivity.putExtra(LoginActivity.AUTOLOGIN, true);

                            startActivity(loginActivity);
                            finish();
                        }
                    });
                    builder.show();

                } else if (status.equalsIgnoreCase(ServerRequest.STATUS_ERROR)) {
                    if (jsonObject.has(ServerRequest.SMS_VERIFICATION_ERROR)) {
                        int verificationErrorCode = jsonObject.getInt(ServerRequest.SMS_VERIFICATION_ERROR);

                        if (verificationErrorCode == 1) {
                            AlertDialog.Builder pleaseTryLogin = new AlertDialog.Builder(RegisterActivity.this);
                            pleaseTryLogin.setMessage(jsonObject.getString("message"));
                            pleaseTryLogin.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startLoginActivityAutoStart(RegisterActivity.this);
                                }
                            });
                            pleaseTryLogin.show();
                        }
                    } else {
                        Toast.makeText(RegisterActivity.this, jsonObject.getString("message"),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
                throw new RuntimeException("Server response cannot be cast to JSONObject");
            }
        }

        @Override
        public void error(int errorCode) {
            Toast.makeText(RegisterActivity.this,
                    " ?!   ?  !",
                    Toast.LENGTH_SHORT).show();
        }
    });
    queryMaster.start();
}

From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java

License:asdf

@Test
public void testRetrieveFIlteredMultipartDatastreams() throws Exception {

    final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest10");
    assertEquals(201, getStatus(objMethod));
    final HttpPost post = new HttpPost(serverAddress + "objects/FedoraDatastreamsTest10/datastreams/");

    final MultipartEntity multiPartEntity = new MultipartEntity();
    multiPartEntity.addPart("ds1", new StringBody("asdfg"));
    multiPartEntity.addPart("ds2", new StringBody("qwerty"));

    post.setEntity(multiPartEntity);// ww w  .  jav a 2 s .  c  om

    final HttpResponse postResponse = client.execute(post);
    assertEquals(201, postResponse.getStatusLine().getStatusCode());

    // TODO: we should actually evaluate the multipart response for the
    // things we're expecting
    final HttpGet getDSesMethod = new HttpGet(
            serverAddress + "objects/FedoraDatastreamsTest10/datastreams/__content__?dsid=ds1");
    final HttpResponse response = client.execute(getDSesMethod);
    assertEquals(200, response.getStatusLine().getStatusCode());
    final String content = EntityUtils.toString(response.getEntity());

    assertTrue("Didn't find the first datastream!", compile("asdfg", DOTALL).matcher(content).find());
    assertFalse("Didn't expect to find the second datastream!",
            compile("qwerty", DOTALL).matcher(content).find());

}

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

/**
 * THis API gets all the submit buttons for Attachment submission
 * Also gets the default values for the selection dropdowns
 * @param docURL//w ww.j a v a2s . c o m
 * @return 
 */
public HashMap<String, ContentBody> getAttachmentEditSubmitInfo(String docURL) {
    HashMap<String, ContentBody> formFields = new HashMap<String, ContentBody>();
    // List<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();
    WebResponse wr = appConnector.getUrl(this.makeEditUrl(docURL), false);

    if (wr.getStatusCode() == 200) {
        Document wfDoc = Jsoup.parse(wr.getResponseBody());
        // get the action buttons
        List<BasicNameValuePair> nvp = this.getActionsViewButtonInfo(wfDoc);
        // filter the action buttons, we want only the save acttion
        for (BasicNameValuePair pair : nvp) {
            try {
                if (pair.getName().equals("form.actions.save")) {
                    formFields.put(pair.getName(), new StringBody(pair.getValue()));
                }
            } catch (UnsupportedEncodingException ex) {
                log.error("Encoding error while adding field " + pair.getName(), ex);
            }
        }
        // get the other defaulted fields
        List<String> defaultFields = new ArrayList<String>() {
            {
                add("form.language");
                add("form.type");
            }
        };
        // get the default values for fields
        for (BasicNameValuePair defField : this.getFormFieldSelectDefaultValues(wfDoc, defaultFields)) {
            try {
                formFields.put(defField.getName(), new StringBody(defField.getValue()));
            } catch (UnsupportedEncodingException ex) {
                log.error("Error encoding field value " + defField.getName(), ex);
            }
        }

    }
    return formFields;
}

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

public String getSecurityToken(String user, String password) throws SecurityException {
    try {//from   ww  w  .ja  v a2  s.c  o 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");
    }/*from  w ww .  ja  va 2 s  .  co m*/

    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:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java

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

    String fileNameAPIM624 = "APIM624.txt";
    String docName = "APIM624PublisherTestHowTo-File-summary";
    String docType = "public forum";
    String sourceType = "file";
    String summary = "Testing";
    String mimeType = "text/plain";
    String docUrl = "http://";
    String filePathAPIM624 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts"
            + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM624;
    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(filePathAPIM624);
    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("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:ro.teodorbaciu.commons.client.ws.BaseWsMethods.java

/**
 * Handles the communication details with the server.
 * /*from   w  ww  .  j av a 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);
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * uploads measurements data as a batch file
 * @param dbIterator/*from   ww w.  j ava 2  s .c o m*/
 * @param latLonFormat
 * @param count
 * @param max
 * @return number of uploaded measurements
 */
private int uploadMeasurementsBatch(MeasurementsDBIterator dbIterator, NumberFormat latLonFormat, int count,
        int max) {
    writeToLog("uploadMeasurementsBatch(" + count + ", " + max + ")");

    try {
        StringBuilder sb = new StringBuilder(
                "lat,lon,mcc,mnc,lac,cellid,signal,measured_at,rating,speed,direction,act\n");

        int thisBatchSize = 0;
        while (thisBatchSize < MEASUREMENTS_BATCH_SIZE && dbIterator.hasNext() && uploadThreadRunning) {
            Measurement meassurement = dbIterator.next();

            sb.append(latLonFormat.format(meassurement.getLat())).append(",");
            sb.append(latLonFormat.format(meassurement.getLon())).append(",");
            sb.append(meassurement.getMcc()).append(",");
            sb.append(meassurement.getMnc()).append(",");
            sb.append(meassurement.getLac()).append(",");
            sb.append(meassurement.getCellid()).append(",");
            sb.append(meassurement.getGsmSignalStrength()).append(",");
            sb.append(meassurement.getTimestamp()).append(",");
            sb.append((meassurement.getAccuracy() != null) ? meassurement.getAccuracy() : "").append(",");
            sb.append((int) meassurement.getSpeed()).append(",");
            sb.append((int) meassurement.getBearing()).append(",");
            sb.append((meassurement.getNetworkType() != null) ? meassurement.getNetworkType() : "");
            sb.append("\n");

            thisBatchSize++;
        }

        HttpResponse response = null;

        writeToLog("Upload request URL: " + httppost.getURI());

        if (uploadThreadRunning) {
            String csv = sb.toString();

            writeToLog("Upload data: " + csv);

            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("key", new StringBody(apiKey));
            mpEntity.addPart("appId", new StringBody(appId));
            mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(csv.getBytes()),
                    "text/csv", MULTIPART_FILENAME));

            ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
            // reqEntity is the MultipartEntity instance
            mpEntity.writeTo(bArrOS);
            bArrOS.flush();
            ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
            bArrOS.close();

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

            httppost.setEntity(bArrEntity);

            response = httpclient.execute(httppost);
            if (response == null) {
                writeToLog("Upload: null HTTP-response");
                throw new IllegalStateException("no HTTP-response from server");
            }

            HttpEntity resEntity = response.getEntity();

            writeToLog(
                    "Upload: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine());

            if (resEntity != null) {
                resEntity.consumeContent();
            }

            if (response.getStatusLine() == null) {
                writeToLog(": " + "null HTTP-status-line");
                throw new IllegalStateException("no HTTP-status returned");
            }

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IllegalStateException(
                        "HTTP-status code returned : " + response.getStatusLine().getStatusCode());
            }
        }

        return count + thisBatchSize;

    } catch (IOException e) {
        throw new IllegalStateException("IO-Error: " + e.getMessage());
    }
}

From source file:setiquest.renderer.Utils.java

/**
 * Send a BSON file.//ww  w.j  av  a  2s.com
 * @param filename the full path to the BSON file.
 * @param actId the activity Id.
 * @param obsId the observation Id.
 * @param pol the POL of thedata.
 * @param subchannel the subchannel of the data.
 */
public static String sendBSONFile(String filename, int actId, int obsId, int pol, String subchannel) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Utils.getSubjectsURL());

    Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:"
            + subchannel);

    FileBody bin = new FileBody(new File(filename));
    try {
        StringBody comment = new StringBody("Filename: " + filename);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", bin);
        reqEntity.addPart("type", new StringBody("data/bson"));
        reqEntity.addPart("subject[activity_id]", new StringBody("" + actId));
        reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId));
        reqEntity.addPart("subject[pol]", new StringBody("" + pol));
        reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel));
        httppost.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        Log.log(response.toString());
        return response.toString();

        /*
           sendResult  = "subject[activity_id]: " + actId + "\n";
           sendResult += "subject[observation_id]: " + obsId + "\n";
           sendResult += "subject[pol]: " + pol + "\n";
           sendResult += "subject[subchannel]: " + subchannel + "\n";
           sendResult += response.toString() + "|\n";
           */

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

From source file:com.stepsdk.android.api.APIClient.java

public HttpEntity postRequest(String url, Map<String, String> params, Map<String, String> files)
        throws NetworkDownException, HttpGetException, HttpPostException, IOException {

    MultipartEntity mpEntity = new CountingMultipartEntity(new ProgressListener() {
        private int prevPercentage = 0;

        @Override/*from   ww w.j  a va  2s .  c  o  m*/
        public void transferred(long num) {
            int percentage = (int) num;
            if (percentage > prevPercentage) {
                prevPercentage = percentage;
            }
        }
    });

    Iterator<Entry<String, String>> i = params.entrySet().iterator();
    while (i.hasNext()) {
        Entry<String, String> next = i.next();
        mpEntity.addPart(next.getKey(), new StringBody(next.getValue()));
    }

    i = files.entrySet().iterator();
    while (i.hasNext()) {
        Entry<String, String> next = i.next();
        mpEntity = addFile(mpEntity, next.getKey(), next.getValue());
    }

    HttpEntity response = httpPost(url, mpEntity);
    return response;
}