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:br.itecbrazil.serviceftpcliente.model.ThreadEnvio.java

private void enviarArquivo(File arquivo, Config config) {
    if (gravarBackup(arquivo)) {
        logger.info("Enviando arquivo " + arquivo.getName() + ". Thread: " + Thread.currentThread().getName());
        try {//  w  w w  .  jav a2  s .  c o m
            HttpClient httpclient = new org.apache.http.impl.client.DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://" + config.getHost() + "/upload");
            httppost.setHeader("X-Requested-With", "XMLHttpRequest");

            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("id", new StringBody(config.getUsuario()));
            mpEntity.addPart("arquivo", new FileBody(arquivo));

            httppost.setEntity(mpEntity);
            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == 200) {
                logger.info("Arquivo arquivo " + arquivo.getName() + " enviado com sucesso. Thread: "
                        + Thread.currentThread().getName());
                atualizarDadoDeEnvio(arquivo);
                arquivo.delete();
                logger.info("Arquivo deletado " + arquivo.getName() + " do diretorio de envio. Thread: "
                        + Thread.currentThread().getName());
            }

        } catch (MalformedURLException ex) {
            loggerExceptionEnvio.info(ex);
        } catch (IOException ex) {
            loggerExceptionEnvio.info(ex);
        }
    }
}

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

/**
 * @param twitter/*from w  w w. j a  va 2  s.co m*/
 *            One of the following values: <br>
 *            "no" - Do not send post to twitter.<br>
 *            "auto" - Send to Twitter with an automatically generated
 *            summary of the post.<br>
 *            Any other value - A custom message to send to Twitter for this
 *            post.
 * @throws UnsupportedEncodingException
 */
public void setTwitter(String twitter) throws UnsupportedEncodingException {
    entity.addPart("send-to-twitter", new StringBody(twitter));
}

From source file:org.apache.sling.testing.tools.sling.SlingClient.java

/** Updates a node at specified path, with optional properties
*///from  ww w . ja  v a  2 s  .c  o m
public void setProperties(String path, Map<String, Object> properties) throws IOException {
    final MultipartEntity entity = new MultipartEntity();
    // Add user properties
    if (properties != null) {
        for (Map.Entry<String, Object> e : properties.entrySet()) {
            entity.addPart(e.getKey(), new StringBody(e.getValue().toString()));
        }
    }

    final HttpResponse response = executor
            .execute(builder.buildPostRequest(path).withEntity(entity).withCredentials(username, password))
            .assertStatus(200).getResponse();
}

From source file:com.mobisys.android.ibp.ObservationRequestQueue.java

private void uploadImage(final boolean single, final Bundle b, final Context context,
        final ArrayList<String> imageStringPath, ArrayList<String> imageType, final ObservationInstance sp) {
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (b != null)
        Log.d("ObservationRequestQueue", "Params: " + b.toString());
    int countUri = 0;
    for (int i = 0; i < imageStringPath.size(); i++) {
        if (!imageStringPath.get(i).contains("http://")) {
            FileBody bab;/*from  w w w.j a  v a 2 s  . c  om*/
            if (imageType.get(i) != null)
                bab = new FileBody(new File(imageStringPath.get(i)), imageType.get(i)); // image path and image type
            else
                bab = new FileBody(new File(imageStringPath.get(i)), "image/jpeg"); // image p   
            reqEntity.addPart("resources", bab);

            ++countUri;
        }
    }

    // if imagestring path has no Image url's.
    if (countUri != 0) {
        try {
            reqEntity.addPart(Request.RESOURCE_TYPE, new StringBody("species.participation.Observation"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        WebService.sendMultiPartRequest(context, Request.METHOD_POST, Request.PATH_UPLOAD_RESOURCE,
                new ResponseHandler() {

                    @Override
                    public void onSuccess(String response) {
                        sp.setStatus(StatusType.PROCESSING);
                        ObservationInstanceTable.updateRowFromTable(context, sp);
                        parseUploadResourceDetail(response, single, b, context, sp, imageStringPath);
                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        Log.d("NetWorkState", content);
                        if (e instanceof UnknownHostException || e instanceof ConnectException) {
                            mIsRunning = false;
                            return;
                        }
                        sp.setStatus(StatusType.FAILURE);
                        sp.setMessage(content);
                        ObservationInstanceTable.updateRowFromTable(context, sp);
                        //ObservationParamsTable.deleteRowFromTable(context, sp);
                        if (!single) {
                            ObservationInstance sp_new = ObservationInstanceTable.getFirstRecord(context);
                            observationMethods(single, sp_new, context);
                        }
                    }
                }, reqEntity);

    } else { // if all are url's
        for (int i = 0; i < imageStringPath.size(); i++) {
            b.putString("file_" + (i + 1), imageStringPath.get(i)
                    .replace("http://" + HttpUtils.stageOrProdBaseURL() + "/biodiv/observations/", ""));
            b.putString("type_" + (i + 1), Constants.IMAGE);
            b.putString("license_" + (i + 1), "CC_BY");
        }
        submitObservationRequestFinally(single, b, context, sp);
    }
}

From source file:edu.scripps.fl.pubchem.web.entrez.EUtilsWebSession.java

private MultipartEntity addParts(MultipartEntity entity, Collection<Object> pairs)
        throws UnsupportedEncodingException {
    Iterator<Object> iter = pairs.iterator();
    while (iter.hasNext()) {
        String name = iter.next().toString();
        String key = iter.hasNext() ? iter.next().toString() : "";
        entity.addPart(name, new StringBody(key.toString()));
    }/*  ww  w. j a v  a  2s.co m*/
    return entity;
}

From source file:com.shmsoft.dmass.lotus.NSFParser.java

private boolean submitProcessing(String url, String taskId, String nsfFile) {
    File file = new File(nsfFile);

    HttpClient httpClient = new DefaultHttpClient();

    try {/*from w  w w  .  j  av  a  2  s . co m*/
        HttpPost post = new HttpPost(url + "/submit-processing.html");

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", new FileBody(file));

        entity.addPart("taskId", new StringBody(taskId));

        post.setEntity(entity);

        HttpResponse response = httpClient.execute(post);
        getResponseMessage(response);
    } catch (Exception e) {
        System.out.println("NSFParser -- Problem sending data: " + e.getMessage());

        return false;
    }

    return true;
}

From source file:com.todoroo.astrid.actfm.sync.ActFmInvoker.java

public JSONObject postSync(String data, MultipartEntity entity, boolean changesHappened, String tok)
        throws IOException, ActFmServiceException {
    try {/* w w w  .j  a  va2  s. c o m*/
        String timeString = DateUtilities.timeToIso8601(DateUtilities.now(), true);

        Object[] params = { "token", tok, "data", data, "time", timeString };

        if (changesHappened) {
            String gcm = Preferences.getStringValue(GCMIntentService.PREF_REGISTRATION);
            ActFmSyncThread.syncLog("Sending GCM token: " + gcm);
            if (!TextUtils.isEmpty(gcm)) {
                params = AndroidUtilities.addToArray(Object.class, params, "gcm", gcm);
                entity.addPart("gcm", new StringBody(gcm));
            }
        }

        String request = createFetchUrl("api/" + API_VERSION, "synchronize", params);
        if (SYNC_DEBUG)
            Log.e("act-fm-post", request);
        Charset chars;
        try {
            chars = Charset.forName("UTF-8");
        } catch (Exception e) {
            chars = null;
        }

        entity.addPart("token", new StringBody(tok));
        entity.addPart("data", new StringBody(data, chars));
        entity.addPart("time", new StringBody(timeString));

        String response = restClient.post(request, entity);
        JSONObject object = new JSONObject(response);

        if (SYNC_DEBUG)
            AndroidUtilities.logJSONObject("act-fm-post-response", object);

        if (object.getString("status").equals("error"))
            throw new ActFmServiceException(object.getString("message"), object);
        return object;
    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String uploadFile(String page, Properties properties, String fileParam, String file)
        throws Exception {
    if (D) {//  ww w  .  ja  v a 2  s . c o m
        RWHtmlLog.i(TAG, "Starting upload of file: " + file, null);
    }

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    MultipartEntity entity = new MultipartEntity();

    Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        entity.addPart(key, new StringBody(val));
        if (D) {
            RWHtmlLog.i(TAG, "Added StringBody multipart for: '" + key + "' = '" + val + "'", null);
        }
    }

    File upload = new File(file);
    entity.addPart(fileParam, new FileBody(upload));
    if (D) {
        String msg = "Added FileBody multipart for: '" + fileParam + "' = <'" + upload.getAbsolutePath()
                + ", size: " + upload.length() + " bytes >'";
        RWHtmlLog.i(TAG, msg, null);
    }

    request.setEntity(entity);

    if (D) {
        RWHtmlLog.i(TAG, "Sending HTTP request...", null);
    }

    HttpResponse response = httpClient.execute(request);

    int st = response.getStatusLine().getStatusCode();

    if (st == HttpStatus.SC_OK) {
        StringBuffer sbResponse = new StringBuffer();
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection

        if (D) {
            RWHtmlLog.i(TAG, "Upload successful (HTTP code: " + st + ")", null);
            RWHtmlLog.i(TAG, "Server response: " + sbResponse.toString(), null);
        }

        return sbResponse.toString();
    } else {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);
        RWHtmlLog.e(TAG, "Upload failed (http code: " + st + ")", null);
        RWHtmlLog.e(TAG, "Server response: " + ostream.toString(), null);
        throw new Exception(HTTP_POST_FAILED + st);
    }
}

From source file:ua.pp.msk.gradle.http.Client.java

public boolean upload(NexusConf nc) throws ArtifactPromotionException {
    boolean result = false;
    String possibleFailReason = "Unknown";
    try {//from  www  .  j a  v  a2  s . c  om
        HttpPost httpPost = new HttpPost(targetUrl.toString());

        MultipartEntity me = new MultipartEntity(HttpMultipartMode.STRICT);
        //            FormBodyPart fbp = new FormBodyPart("form", new StringBody("check it"));
        //            fbp.addField("r", nc.getRepository());
        //            fbp.addField("hasPom", "" + nc.isHasPom());
        //            fbp.addField("e", nc.getExtension());
        //            fbp.addField("g", nc.getGroup());
        //            fbp.addField("a", nc.getArtifact());
        //            fbp.addField("v", nc.getVersion());
        //            fbp.addField("p", nc.getPackaging());
        //            me.addPart(fbp);
        File rpmFile = new File(nc.getFile());
        ContentBody cb = new FileBody(rpmFile);
        me.addPart("p", new StringBody(nc.getPackaging()));
        me.addPart("e", new StringBody(nc.getExtension()));
        me.addPart("r", new StringBody(nc.getRepository()));
        me.addPart("g", new StringBody(nc.getGroup()));
        me.addPart("a", new StringBody(nc.getArtifact()));
        me.addPart("v", new StringBody(nc.getVersion()));
        me.addPart("c", new StringBody(nc.getClassifier()));
        me.addPart("file", cb);

        httpPost.setHeader("User-Agent", userAgent);
        httpPost.setEntity(me);

        logger.debug("Sending request");
        HttpResponse postResponse = client.execute(httpPost, context);
        logger.debug("Status line: " + postResponse.getStatusLine().toString());
        int statusCode = postResponse.getStatusLine().getStatusCode();

        HttpEntity entity = postResponse.getEntity();

        try (BufferedReader bufReader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
            StringBuilder fsb = new StringBuilder();
            bufReader.lines().forEach(e -> {
                logger.debug(e);
                fsb.append(e);
                fsb.append("\n");
            });
            possibleFailReason = fsb.toString();
        } catch (IOException ex) {
            logger.warn("Cannot get entity response", ex);
        }

        switch (statusCode) {
        case 200:
            logger.debug("Got a successful http response " + postResponse.getStatusLine());
            result = true;
            break;
        case 201:
            logger.debug("Created! Got a successful http response " + postResponse.getStatusLine());
            result = true;
            break;
        case 401:
            throw new BadCredentialsException(
                    "Bad credentials. Response status: " + postResponse.getStatusLine());
        default:
            throw new ResponseException(
                    String.format("Response is not OK. Response status: %s\n\tPossible reason: %s",
                            postResponse.getStatusLine(), possibleFailReason));
        }

        EntityUtils.consume(entity);

    } catch (UnsupportedEncodingException ex) {
        logger.error("Encoding is unsuported ", ex);
        throw new ArtifactPromotionException("Encoding is unsuported " + ex.getMessage());
    } catch (IOException ex) {
        logger.error("Got IO excepption ", ex);
        throw new ArtifactPromotionException("Input/Output error " + ex.getMessage());
    } catch (ResponseException | BadCredentialsException ex) {
        logger.error("Cannot upload artifact", ex);
        throw new ArtifactPromotionException("Cannot upload artifact " + ex.getMessage());
    }
    return result;
}

From source file:org.bimserver.client.Channel.java

public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid,
        boolean merge, boolean sync, long fileSize, String filename, InputStream inputStream)
        throws ServerException, UserException {
    String address = baseAddress + "/upload";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }/*from   ww w. j  av  a  2s . c o  m*/
        }
    });

    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    HttpPost httppost = new HttpPost(address);
    try {
        // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now
        InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("data", data);
        reqEntity.addPart("token", new StringBody(token));
        reqEntity.addPart("deserializerOid", new StringBody("" + deserializerOid));
        reqEntity.addPart("merge", new StringBody("" + merge));
        reqEntity.addPart("poid", new StringBody("" + poid));
        reqEntity.addPart("comment", new StringBody("" + comment));
        reqEntity.addPart("sync", new StringBody("" + sync));
        reqEntity.addPart("compression", new StringBody("deflate"));
        httppost.setEntity(reqEntity);

        HttpResponse httpResponse = httpclient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            JsonParser jsonParser = new JsonParser();
            JsonElement result = jsonParser
                    .parse(new JsonReader(new InputStreamReader(httpResponse.getEntity().getContent())));
            if (result instanceof JsonObject) {
                JsonObject jsonObject = (JsonObject) result;
                if (jsonObject.has("exception")) {
                    JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject();
                    String exceptionType = exceptionJson.get("__type").getAsString();
                    String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString()
                            : "unknown";
                    if (exceptionType.equals(UserException.class.getSimpleName())) {
                        throw new UserException(message);
                    } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                        throw new ServerException(message);
                    }
                } else {
                    return jsonObject.get("checkinid").getAsLong();
                }
            }
        }
    } catch (ClientProtocolException e) {
        LOGGER.error("", e);
    } catch (IOException e) {
        LOGGER.error("", e);
    }
    return -1;
}