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: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);
                }/*from  ww  w  . j a v a2 s. c om*/
            }
        }
        return entity;
    };
}

From source file:com.testmax.util.FileUtility.java

public void fileUpload(String url, String filename) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    FileBody fileContent = new FileBody(new File(filename));
    try {//from  w ww .  ja v a 2  s .  com
        StringBody comment = new StringBody("Filename: " + filename);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("file", fileContent);
    httppost.setEntity(reqEntity);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpEntity resEntity = response.getEntity();
}

From source file:org.trpr.platform.batch.impl.job.ha.service.SyncServiceImpl.java

/**
 * Interface Method Implementation/* w  ww .ja  va2 s.  c  om*/
 * @see SyncService#pushJobToHost(String, String)
 */
public boolean pushJobToHost(String jobName, String serverName) {
    serverName = SyncServiceImpl.PROTOCOL + serverName + SynchronizationController.PUSH_URL;

    HttpPost postRequest = new HttpPost(serverName);
    try {
        MultipartEntity multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("jobName", new StringBody(jobName));

        FileBody fileBody = new FileBody(this.jobConfigService.getJobConfig(jobName).getFile(),
                "application/octect-stream");
        multiPartEntity.addPart("jobConfig", fileBody);

        if (this.jobConfigService.getJobDependencyList(jobName) != null) {
            for (String dependency : this.jobConfigService.getJobDependencyList(jobName)) {
                File depFile = new File(
                        this.jobConfigService.getJobStoreURI(jobName).getPath() + "/lib/" + dependency);
                FileBody depFileBody = new FileBody(depFile);
                multiPartEntity.addPart("depFiles[]", depFileBody);
            }
        }
        postRequest.setEntity(multiPartEntity);
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Error while forming multiPart request", ex);
    } catch (IOException e) {
        LOGGER.error("Error while forming multiPart request", e);
    }
    String retValue = org.trpr.platform.batch.impl.job.ha.service.FileUpload.executeRequest(postRequest);
    LOGGER.info("Server returns: " + retValue.trim());
    if (retValue.trim().equalsIgnoreCase(SyncServiceImpl.SUCCESS_STRING)) {
        return true;
    }
    return false;
}

From source file:dk.kasperbaago.JSONHandler.JSONHandler.java

public String getURL() {

    //Making a HTTP client
    HttpClient client = new DefaultHttpClient();

    //Declaring HTTP response
    HttpResponse response = null;//w  w  w .  j  av a2  s.  c  o  m
    String myReturn = null;

    try {

        //Making a HTTP getRequest or post request
        if (method == "get") {
            String parms = "";
            if (this.parameters.size() > 0) {
                parms = "?";
                parms += URLEncodedUtils.format(this.parameters, "utf-8");
            }

            Log.i("parm", parms);
            Log.i("URL", this.url + parms);
            HttpGet getUrl = new HttpGet(this.url + parms);

            //Executing the request
            response = client.execute(getUrl);
        } else if (method == "post") {
            HttpPost getUrl = new HttpPost(this.url);

            //Sets parameters to add
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (int i = 0; i < this.parameters.size(); i++) {
                if (this.parameters.get(i).getName().equalsIgnoreCase(fileField)) {
                    entity.addPart(parameters.get(i).getName(),
                            new FileBody(new File(parameters.get(i).getValue())));
                } else {
                    entity.addPart(parameters.get(i).getName(), new StringBody(parameters.get(i).getName()));
                }
            }

            getUrl.setEntity(entity);

            //Executing the request
            response = client.execute(getUrl);
        } else {
            return "false";
        }

        //Returns the data      
        HttpEntity content = response.getEntity();
        InputStream mainContent = content.getContent();
        myReturn = this.convertToString(mainContent);
        this.HTML = myReturn;
        Log.i("Result", myReturn);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return myReturn;
}

From source file:net.asplode.tumblr.Post.java

/**
 * @param state/*from   ww w  .  j  a  v  a  2s. c o  m*/
 *            Post state.
 * @see State
 * @throws UnsupportedEncodingException
 */
public void setState(State state) throws UnsupportedEncodingException {
    entity.addPart("state", new StringBody(state.getState()));
}

From source file:eu.liveandgov.ar.utilities.OS_Utils.java

/**
 * Remotely recognize captured image//w  w  w .  ja v a 2s .co  m
 * 
 * @param url
 * @param nameValuePairs
 */
public static HttpResponse remote_rec(String url, List<NameValuePair> nameValuePairs, Context ctx) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (int index = 0; index < nameValuePairs.size(); index++) {

            if (nameValuePairs.get(index).getName().equalsIgnoreCase("upload"))
                entity.addPart("upload", new FileBody(new File(nameValuePairs.get(index).getValue())));
            else
                entity.addPart(nameValuePairs.get(index).getName(),
                        new StringBody(nameValuePairs.get(index).getValue()));
        }

        httpPost.setEntity(entity);
        HttpResponse httpresponse = httpClient.execute(httpPost, localContext);

        return httpresponse;

    } catch (Exception e) {
        //Toast.makeText(ctx, "Can not send for recognition. Internet accessible?", Toast.LENGTH_LONG).show();
        Log.e("ERROR", "Can not send for recognition. Internet accessible?");
        return null;
    }

}

From source file:at.ac.tuwien.big.testsuite.impl.validator.XhtmlValidator.java

@Override
public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception {
    HttpPost request = new HttpPost(W3C_XHTML_VALIDATOR_URL);
    List<ValidationResultEntry> validationResultEntries = new ArrayList<>();

    try {/*  ww w  .  j  a  v  a  2 s.  c om*/
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("uploaded_file", new FileBody(fileToValidate, "text/html"));
        multipartEntity.addPart("charset", new StringBody("(detect automatically)"));
        multipartEntity.addPart("doctype", new StringBody("Inline"));
        multipartEntity.addPart("group", new StringBody("0"));

        request.setEntity(multipartEntity);
        Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request));

        String doctype = DomUtils.textByXpath(doc.getDocumentElement(),
                "//form[@id='form']/table//tr[4]/td[1]");

        if (!"XHTML 1.1".equals(doctype.trim()) && !doctype.contains("XHTML+ARIA 1.0")) {
            validationResultEntries.add(new DefaultValidationResultEntry("Doctype Validation",
                    "The given document is not XHTML 1.1 compatible, instead the guessed doctype is '" + doctype
                            + "'",
                    ValidationResultEntryType.ERROR));
        }

        Document fileToValidateDocument = null;

        Element warningsContainer = DomUtils.byId(doc.getDocumentElement(), "warnings");

        if (warningsContainer != null) {
            for (Element warningChildElement : DomUtils.asList(warningsContainer.getChildNodes())) {
                if (IGNORED_MESSAGES.contains(warningChildElement.getAttribute("id"))) {
                    continue;
                }

                ValidationResultEntryType type = getEntryType(warningChildElement.getAttribute("class"));
                String title = getTitle(
                        DomUtils.firstByClass(warningChildElement.getElementsByTagName("span"), "msg"));
                StringBuilder descriptionSb = new StringBuilder();

                for (Element descriptionElement : DomUtils.listByXpath(warningChildElement,
                        ".//p[position()>1]")) {
                    descriptionSb.append(descriptionElement.getTextContent());
                }

                validationResultEntries
                        .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type));
            }
        }

        Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "error_loop");

        if (errorsContainer != null) {
            for (Element errorChildElement : DomUtils.asList(errorsContainer.getChildNodes())) {
                ValidationResultEntryType type = getEntryType(errorChildElement.getAttribute("class"));
                StringBuilder titleSb = new StringBuilder();
                NodeList errorEms = errorChildElement.getElementsByTagName("em");

                if (errorEms.getLength() > 0) {
                    titleSb.append(getTitle((Element) errorEms.item(0)));
                    titleSb.append(": ");
                }

                titleSb.append(
                        getTitle(DomUtils.firstByClass(errorChildElement.getElementsByTagName("span"), "msg")));
                StringBuilder descriptionSb = new StringBuilder();

                for (Element descriptionElement : DomUtils.listByXpath(errorChildElement, ".//div/p")) {
                    descriptionSb.append(descriptionElement.getTextContent());
                }

                String title = titleSb.toString();

                if (TestsuiteConstants.EX_ID_LAB3.equals(exerciseId)) {
                    // This is more a hack than anything else but we have to ignore the errors that were produced by JSF specific artifacts.
                    // We basically extract the line and column number from the reported errors and look for the 2 elements that match these
                    // numbers and check if they really are the input elements produced by forms that cant be wrapped by block containers.
                    // More specifically we check for inputs with type hidden, one is for the ViewState of JSF and the other is for recognition
                    // of the form that was submitted.
                    Matcher matcher = LINE_AND_COLUMN_NUMBER_PATTERN.matcher(title);

                    if (title.contains("document type does not allow element \"input\" here")
                            && matcher.matches()) {
                        if (fileToValidateDocument == null) {
                            fileToValidateDocument = DomUtils.createDocument(fileToValidate);
                        }

                        boolean excludeEntry = false;
                        int expectedLineNumber = Integer.parseInt(matcher.group(1));
                        int expectedColumnNumber = Integer.parseInt(matcher.group(2));

                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(new FileInputStream(fileToValidate)))) {
                            String line;

                            while ((line = reader.readLine()) != null) {
                                if (--expectedLineNumber == 0) {
                                    Matcher lineMatcher = HIDDEN_FORM_INPUT_PATTERN.matcher(line);

                                    if (lineMatcher.matches()) {
                                        MatchResult matchResult = lineMatcher.toMatchResult();
                                        if (matchResult.start(1) <= expectedColumnNumber
                                                && matchResult.end(1) >= expectedColumnNumber) {
                                            excludeEntry = true;
                                            break;
                                        }
                                    }

                                    lineMatcher = HIDDEN_VIEW_STATE_INPUT_PATTERN.matcher(line);

                                    if (lineMatcher.matches()) {
                                        MatchResult matchResult = lineMatcher.toMatchResult();
                                        if (matchResult.start(1) <= expectedColumnNumber
                                                && matchResult.end(1) >= expectedColumnNumber) {
                                            excludeEntry = true;
                                            break;
                                        }
                                    }

                                    System.out.println("Could not match potential wrong error.");

                                    break;
                                }
                            }
                        }

                        if (excludeEntry) {
                            continue;
                        }
                    }
                }

                validationResultEntries
                        .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type));
            }
        }
    } finally {
        request.releaseConnection();
    }

    return new DefaultValidationResult("XHTML Validation", fileToValidate.getName(),
            new DefaultValidationResultType("XHTML"), validationResultEntries);
}

From source file:net.asplode.tumblr.Post.java

/**
 * @param tags//  ww  w .j a v  a2 s.com
 *            Comma-separated list of post tags
 * @throws UnsupportedEncodingException
 */
public void setTags(String tags) throws UnsupportedEncodingException {
    entity.addPart("tags", new StringBody(tags));
}

From source file:be.samey.io.ServerConn.java

private HttpEntity makeEntity(String baits, String[] names, Path[] filepaths, double poscutoff,
        double negcutoff, String[] orthNames, Path[] orthPaths) throws UnsupportedEncodingException {

    MultipartEntityBuilder mpeb = MultipartEntityBuilder.create();

    //make hidden form fields, to the server knows to use the api
    mpeb.addPart("__controller", new StringBody("api"));
    mpeb.addPart("__action", new StringBody("execute_job"));

    //make the bait part
    StringBody baitspart = new StringBody(baits, ContentType.TEXT_PLAIN);
    mpeb.addPart("baits", baitspart);

    //make the species file upload parts
    for (int i = 0; i < CyModel.MAX_SPECIES_COUNT; i++) {
        if (i < names.length && i < filepaths.length) {
            mpeb.addBinaryBody("matrix[]", filepaths[i].toFile(), ContentType.TEXT_PLAIN, names[i]);
        }//from   w  ww .j  a  v  a 2s  . co  m
    }

    //make the cutoff parts
    StringBody poscpart = new StringBody(Double.toString(poscutoff));
    mpeb.addPart("positive_correlation", poscpart);
    StringBody negcpart = new StringBody(Double.toString(negcutoff));
    mpeb.addPart("negative_correlation", negcpart);

    //make the orthgroup file upload parts
    for (int i = 0; i < CyModel.MAX_ORTHGROUP_COUNT; i++) {
        if (cyModel.getOrthGroupPaths() != null && i < orthNames.length && i < orthPaths.length) {
            mpeb.addBinaryBody("orthologs[]", orthPaths[i].toFile(), ContentType.TEXT_PLAIN, orthNames[i]);
        }
    }

    return mpeb.build();
}