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, Charset charset) throws UnsupportedEncodingException 

Source Link

Usage

From source file:org.ez.flickr.api.CommandArguments.java

public MultipartEntity getBody(Map<String, String> additionalParameters) {
    try {//  w  ww . j ava 2  s . co m
        MultipartEntity entity = new MultipartEntity();

        for (Parameter param : params) {
            if (!param.internal) {
                if (param.value instanceof File) {
                    entity.addPart(param.key, new FileBody((File) param.value));
                } else if (param.value instanceof String) {
                    entity.addPart(param.key, new StringBody((String) param.value, UTF8));
                }
            }
        }
        for (Map.Entry<String, String> entry : additionalParameters.entrySet()) {
            entity.addPart(entry.getKey(), new StringBody(entry.getValue(), UTF8));
        }

        return entity;

    } catch (UnsupportedEncodingException ex) {
        throw new UnsupportedOperationException(ex.getMessage(), ex);
    }
}

From source file:gov.nist.appvet.tool.sigverifier.util.ReportUtil.java

/** This method should be used for sending files back to AppVet. */
public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    HttpConnectionParams.setSoTimeout(httpParameters, 1200000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpClient = SSLWrapper.wrapClient(httpClient);

    try {//from w  w w  .  java2s  .c o  m
        /*
         * To send reports back to AppVet, the following parameters must be
         * sent: - command: SUBMIT_REPORT - username: AppVet username -
         * password: AppVet password - appid: The app ID - toolid: The ID of
         * this tool - toolrisk: The risk assessment (LOW, MODERATE, HIGH,
         * ERROR) - report: The report file.
         */
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8")));
        entity.addPart("username", new StringBody(Properties.appvetUsername, Charset.forName("UTF-8")));
        entity.addPart("password", new StringBody(Properties.appvetPassword, Charset.forName("UTF-8")));
        entity.addPart("appid", new StringBody(appId, Charset.forName("UTF-8")));
        entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8")));
        entity.addPart("toolrisk", new StringBody(reportStatus.name(), Charset.forName("UTF-8")));
        File report = new File(reportFilePath);
        FileBody fileBody = new FileBody(report);
        entity.addPart("file", fileBody);
        HttpPost httpPost = new HttpPost(Properties.appvetUrl);
        httpPost.setEntity(entity);
        // Send the report to AppVet
        log.debug("Sending report file to AppVet");
        final HttpResponse response = httpClient.execute(httpPost);
        log.debug("Received from AppVet: " + response.getStatusLine());
        HttpEntity httpEntity = response.getEntity();
        InputStream is = httpEntity.getContent();
        String result = IOUtils.toString(is, "UTF-8");
        log.info(result);
        // Clean up
        httpPost = null;
        return true;
    } catch (Exception e) {
        log.error(e.toString());
        return false;
    }
}

From source file:cn.vlabs.duckling.vwb.service.ddl.RestClient.java

private HttpEntity buildMultiPartForm(String dataFieldName, String filename, InputStream stream,
        String... params) {//from w  w  w . j  av a  2 s  . c o m
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody(dataFieldName, stream, ContentType.DEFAULT_BINARY, filename);

    if (params != null) {
        for (int i = 0; i < params.length / 2; i++) {
            StringBody contentBody = new StringBody(params[i * 2 + 1], DEFAULT_CONTENT_TYPE);
            builder.addPart(params[i * 2], contentBody);
        }
    }

    HttpEntity reqEntity = builder.setCharset(DEFAULT_CHARSET).build();
    return reqEntity;
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;//from   w ww.  ja v  a  2 s .  co  m
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);//from w  w w.j  av a 2s  .  co m
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:ch.tatool.app.service.export.DataImportTest.java

private static HttpEntity getHttpEntity() {
    // we use a multipart entity to send over the files
    MultipartEntity entity = new MultipartEntity();

    // get participant information for training (anonymous coded data)
    String participant = "1";

    // add some additional data
    try {/*from  www .  j  a  v a 2 s  .c  om*/
        Charset utf8CharSet = Charset.forName("UTF-8");
        entity.addPart("participant", new StringBody(participant, utf8CharSet));
    } catch (UnsupportedEncodingException e) {
        // should not happen
    }

    return entity;
}

From source file:com.alta189.deskbin.services.image.ImgurService.java

@Override
public String upload(File image) throws ImageServiceException {
    try {//from   w  ww  .  java2s  .  co  m
        HttpPost post = new HttpPost(UPLOAD_URL);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("key", new StringBody(apikey, Charset.forName("UTF-8")));
        entity.addPart("type", new StringBody("file", Charset.forName("UTF-8")));
        FileBody fileBody = new FileBody(image);
        entity.addPart("image", fileBody);
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ImageServiceException(
                    "Error accessing imgur. Status code: " + response.getStatusLine().getStatusCode());
        }
        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = new JSONObject(json).getJSONObject("upload").getJSONObject("links");
        return jsonObject.getString("imgur_page");
    } catch (Exception e) {
        throw new ImageServiceException(e);
    }
}

From source file:com.ibm.watson.developer_cloud.visual_recognition.v1.VisualRecognition.java

/**
 * Classifies the images against the label groups and labels. The response
 * includes a score for a label if the score meets the minimum threshold of
 * 0.5. If no score meets the threshold for an image, no labels are
 * returned./*from   w ww .  j  a  v a  2  s.co m*/
 * 
 * @param image
 *            the file image
 * @param labelSet
 *            the labels to classify against
 * @return the visual recognition images
 */
public RecognizedImage recognize(final File image, final LabelSet labelSet) {
    if (image == null)
        throw new IllegalArgumentException("image can not be null");
    try {

        Request request = Request.Post("/v1/tag/recognize");

        MultipartEntity reqEntity = new MultipartEntity();

        // Set the image_file
        FileBody bin = new FileBody(image);
        reqEntity.addPart(IMG_FILE, bin);

        if (labelSet != null) {
            StringBody labels = new StringBody(GsonSingleton.getGson().toJson(labelSet),
                    Charset.forName("UTF-8"));

            // Set the labels_to_check
            reqEntity.addPart(LABELS_TO_CHECK, labels);
        }
        request.withEntity(reqEntity);

        HttpResponse response = execute(request.build());
        String resultJson = ResponseUtil.getString(response);
        VisualRecognitionImages recognizedImages = GsonSingleton.getGson().fromJson(resultJson,
                VisualRecognitionImages.class);
        return recognizedImages.getImages().get(0);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:bluej.collect.CollectUtility.java

/**
 * Converts the given String to a StringBody.  Null strings are sent the same as empty strings.
 *///from  w  ww .jav a  2  s  .  co m
static StringBody toBody(String s) {
    try {
        return new StringBody(s == null ? "" : s, utf8);
    } catch (UnsupportedEncodingException e) {
        // Shouldn't happen, because UTF-8 is required to be supported
        return null;
    }
}