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:com.uf.togathor.db.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws IOException, UnsupportedOperationException {
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding/*from  www .j a  v  a  2  s . c  om*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * @param reqEntity/* w  w  w  .  j  a  v  a  2  s . c om*/
 * @param params
 * @param charset
 */
public void buildParameters(MultipartEntityBuilder reqEntity, Map<String, String> params, Charset charset) {

    if (params != null && !params.isEmpty()) {

        ContentType contentType = ContentType.TEXT_PLAIN.withCharset(charset);

        for (Map.Entry<String, String> entry : params.entrySet()) {

            if (entry.getKey() == null)
                continue;

            String value = entry.getValue();

            if (value == null)
                value = "";

            reqEntity.addPart(entry.getKey(), new StringBody(value, contentType));
        }
    }
}

From source file:com.gorillalogic.monkeytalk.ant.RunTask.java

private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException {

    HttpClient base = new DefaultHttpClient();
    SSLContext ctx = null;/* w  ww . jav  a  2s .  com*/

    try {
        ctx = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException ex) {
        log("exception in sendFormPost():");
    }

    X509TrustManager tm = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }
    };

    try {
        ctx.init(null, new TrustManager[] { tm }, null);
    } catch (KeyManagementException ex) {
        log("exception in sendFormPost():");
    }

    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));

    HttpClient client = new DefaultHttpClient(ccm, base.getParams());
    try {
        HttpPost post = new HttpPost(url);

        MultipartEntity multipart = new MultipartEntity();
        for (String key : additionalParams.keySet())
            multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8")));

        if (proj != null) {
            multipart.addPart("uploaded_file", new FileBody(proj));
        }

        post.setEntity(multipart);

        HttpResponse resp = client.execute(post);

        HttpEntity out = resp.getEntity();

        InputStream in = out.getContent();
        return FileUtils.readStream(in);
    } catch (Exception ex) {
        throw new IOException("POST failed", ex);
    } finally {
        try {
            client.getConnectionManager().shutdown();
        } catch (Exception ex) {
            // ignore
        }
    }
}

From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java

private void addPart(MultipartEntity multipart, String key, Object value) throws UnsupportedEncodingException {
    if (value instanceof String[]) {
        String[] v = (String[]) value;
        for (String s : v) {
            multipart.addPart(key, new StringBody(s, Charset.forName("UTF-8")));
        }//ww  w  .j av  a2  s.c o  m
    } else {
        multipart.addPart(key, new StringBody((String) value, Charset.forName("UTF-8")));
    }
}

From source file:org.brutusin.rpc.client.http.HttpEndpoint.java

private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod,
        final ProgressCallback progressCallback) throws IOException {
    RpcRequest request = new RpcRequest();
    request.setJsonrpc("2.0");
    request.setMethod(serviceId);/*from   w w  w .  ja  va 2 s.c  o m*/
    request.setParams(input);
    final String payload = JsonCodec.getInstance().transform(request);
    final HttpUriRequest req;
    if (httpMethod == HttpMethod.GET) {
        String urlparam = URLEncoder.encode(payload, "UTF-8");
        req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam);
    } else {
        HttpEntityEnclosingRequestBase reqBase;
        if (httpMethod == HttpMethod.POST) {
            reqBase = new HttpPost(this.endpoint);
        } else if (httpMethod == HttpMethod.PUT) {
            reqBase = new HttpPut(this.endpoint);
        } else {
            throw new AssertionError();
        }
        req = reqBase;
        HttpEntity entity;
        Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.STRICT);
        builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON));
        if (files != null && !files.isEmpty()) {
            files = sortFiles(files);
            for (Map.Entry<String, InputStream> entrySet : files.entrySet()) {
                String key = entrySet.getKey();
                InputStream is = entrySet.getValue();
                if (is instanceof MetaDataInputStream) {
                    MetaDataInputStream mis = (MetaDataInputStream) is;
                    builder.addPart(key, new InputStreamBody(mis, mis.getName()));
                } else {
                    builder.addPart(key, new InputStreamBody(is, key));
                }
            }
        }
        entity = builder.build();
        if (progressCallback != null) {
            entity = new ProgressHttpEntityWrapper(entity, progressCallback);
        }
        reqBase.setEntity(entity);
    }
    HttpClientContext context = contexts.get();
    if (this.clientContextFactory != null && context == null) {
        context = clientContextFactory.create();
        contexts.set(context);
    }
    return this.httpClient.execute(req, context);
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

public static FanWallMessage postMessage(String msg, String imagePath, int parentId, int replyId,
        boolean withGps) {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient httpClient = new DefaultHttpClient(params);

    try {/*from   w  ww . ja  v  a2  s.c o  m*/
        HttpPost httpPost = new HttpPost(Statics.BASE_URL + "/");

        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("app_id",
                new StringBody(com.appbuilder.sdk.android.Statics.appId, Charset.forName("UTF-8")));
        multipartEntity.addPart("token",
                new StringBody(com.appbuilder.sdk.android.Statics.appToken, Charset.forName("UTF-8")));
        multipartEntity.addPart("module_id", new StringBody(Statics.MODULE_ID, Charset.forName("UTF-8")));

        // ? ?
        multipartEntity.addPart("parent_id",
                new StringBody(Integer.toString(parentId), Charset.forName("UTF-8")));
        multipartEntity.addPart("reply_id",
                new StringBody(Integer.toString(replyId), Charset.forName("UTF-8")));

        if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
            multipartEntity.addPart("account_type", new StringBody("facebook", Charset.forName("UTF-8")));
        } else if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
            multipartEntity.addPart("account_type", new StringBody("twitter", Charset.forName("UTF-8")));
        } else {
            multipartEntity.addPart("account_type", new StringBody("ibuildapp", Charset.forName("UTF-8")));
        }
        multipartEntity.addPart("account_id",
                new StringBody(Authorization.getAuthorizedUser().getAccountId(), Charset.forName("UTF-8")));
        multipartEntity.addPart("user_name",
                new StringBody(Authorization.getAuthorizedUser().getUserName(), Charset.forName("UTF-8")));
        multipartEntity.addPart("user_avatar",
                new StringBody(Authorization.getAuthorizedUser().getAvatarUrl(), Charset.forName("UTF-8")));

        if (withGps) {
            if (Statics.currentLocation != null) {
                multipartEntity.addPart("latitude",
                        new StringBody(Statics.currentLocation.getLatitude() + "", Charset.forName("UTF-8")));
                multipartEntity.addPart("longitude",
                        new StringBody(Statics.currentLocation.getLongitude() + "", Charset.forName("UTF-8")));
            }
        }

        multipartEntity.addPart("text", new StringBody(msg, Charset.forName("UTF-8")));

        if (!TextUtils.isEmpty(imagePath)) {
            multipartEntity.addPart("images", new FileBody(new File(imagePath)));
        }

        httpPost.setEntity(multipartEntity);

        String resp = httpClient.execute(httpPost, new BasicResponseHandler());

        return JSONParser.parseMessagesString(resp).get(0);

    } catch (Exception e) {
        return null;
    }
}

From source file:org.wisdom.framework.vertx.FileUploadTest.java

@Test
public void testThatFileUpdateFailedWhenTheFileExceedTheConfiguredSize()
        throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE))
            .thenReturn(DiskFileUpload.MINSIZE);
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(10l); // 10 bytes max
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok();
        }/*from  w  w w. j av a 2s.  c om*/
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);

    ContentEngine contentEngine = getMockContentEngine();

    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null,
            Collections.<ExceptionMapper>emptyList());
    server.configuration = configuration;
    server.vertx = vertx;
    server.start();

    VertxHttpServerTest.waitForStart(server);

    int port = server.httpPort();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + 1);

    ByteArrayBody body = new ByteArrayBody("this is too much...".getBytes(), "my-file.dat");
    StringBody description = new StringBody("my description", ContentType.TEXT_PLAIN);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("upload", body).addPart("comment", description)
            .build();

    post.setEntity(entity);

    CloseableHttpResponse response = httpclient.execute(post);
    // We should receive a Payload too large response (413)
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(413);

}

From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java

protected HttpRequestBase createMethod(final SolrRequest request, String collection)
        throws IOException, SolrServerException {

    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;/* w  w  w. j  a v a 2s  .c om*/
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }

    String basePath = baseUrl;
    if (collection != null)
        basePath += "/" + collection;

    if (SolrRequest.METHOD.GET == request.getMethod()) {
        if (streams != null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
        }

        return new HttpGet(basePath + path + wparams.toQueryString());
    }

    if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {

        String url = basePath + path;
        boolean hasNullStreamName = false;
        if (streams != null) {
            for (ContentStream cs : streams) {
                if (cs.getName() == null) {
                    hasNullStreamName = true;
                    break;
                }
            }
        }
        boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod())
                || (streams != null && streams.size() > 1)) && !hasNullStreamName;

        LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
        if (streams == null || isMultipart) {
            // send server list and request list as query string params
            ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
            queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
            String fullQueryUrl = url + queryParams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod()
                    ? new HttpPost(fullQueryUrl)
                    : new HttpPut(fullQueryUrl);

            if (!isMultipart) {
                postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }

            List<FormBodyPart> parts = new LinkedList<>();
            Iterator<String> iter = wparams.getParameterNamesIterator();
            while (iter.hasNext()) {
                String p = iter.next();
                String[] vals = wparams.getParams(p);
                if (vals != null) {
                    for (String v : vals) {
                        if (isMultipart) {
                            parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                        } else {
                            postOrPutParams.add(new BasicNameValuePair(p, v));
                        }
                    }
                }
            }

            // TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder}
            if (isMultipart && streams != null) {
                for (ContentStream content : streams) {
                    String contentType = content.getContentType();
                    if (contentType == null) {
                        contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
                    }
                    String name = content.getName();
                    if (name == null) {
                        name = "";
                    }
                    parts.add(new FormBodyPart(name,
                            new InputStreamBody(content.getStream(), contentType, content.getName())));
                }
            }

            if (parts.size() > 0) {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                for (FormBodyPart p : parts) {
                    entity.addPart(p);
                }
                postOrPut.setEntity(entity);
            } else {
                //not using multipart
                postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
            }

            return postOrPut;
        }
        // It is has one stream, it is the post body, put the params in the URL
        else {
            String fullQueryUrl = url + wparams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod()
                    ? new HttpPost(fullQueryUrl)
                    : new HttpPut(fullQueryUrl);

            // Single stream as body
            // Using a loop just to get the first one
            final ContentStream[] contentStream = new ContentStream[1];
            for (ContentStream content : streams) {
                contentStream[0] = content;
                break;
            }
            if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(
                        new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
                            @Override
                            public Header getContentType() {
                                return new BasicHeader("Content-Type", contentStream[0].getContentType());
                            }

                            @Override
                            public boolean isRepeatable() {
                                return false;
                            }

                        });
            } else {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(
                        new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
                            @Override
                            public Header getContentType() {
                                return new BasicHeader("Content-Type", contentStream[0].getContentType());
                            }

                            @Override
                            public boolean isRepeatable() {
                                return false;
                            }
                        });
            }
            return postOrPut;
        }
    }

    throw new SolrServerException("Unsupported method: " + request.getMethod());

}

From source file:com.poomoo.edao.activity.UploadPicsActivity.java

private void upload(File file) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(eDaoClientConfig.imageurl); // ?Post?,Post
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, eDaoClientConfig.timeout);
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, eDaoClientConfig.timeout);

    MultipartEntity entity = new MultipartEntity(); // ,
    // List<File> list = new ArrayList<File>();
    // // File/*  w  ww .  jav a 2  s  .co m*/
    // list.add(file1);
    // list.add(file2);
    // list.add(file3);
    // list.add(file4);
    // System.out.println("list.size():" + list.size());
    // for (int i = 0; i < list.size(); i++) {
    // ContentBody body = new FileBody(list.get(i));
    // entity.addPart("file", body); // ???
    // }
    System.out.println(
            "upload" + "uploadCount" + ":" + uploadCount + "filelist.size" + ":" + filelist.size());
    entity.addPart("file", new FileBody(file));

    post.setEntity(entity); // ?Post?
    Message message = new Message();
    try {
        entity.addPart("imageType", new StringBody(String.valueOf(uploadCount + 1), Charset.forName("utf-8")));
        entity.addPart("userId", new StringBody(userId, Charset.forName("utf-8")));
        HttpResponse response;
        response = client.execute(post);
        // Post
        if (response.getStatusLine().getStatusCode() == 200) {
            uploadCount++;
            message.what = 1;
        } else
            message.what = 2;
        // return EntityUtils.toString(response.getEntity(), "UTF-8"); //
        // ??
    } catch (Exception e) {
        // TODO ? catch ?
        e.printStackTrace();
        message.what = 2;
        System.out.println("IOException:" + e.getMessage());
    } finally {
        client.getConnectionManager().shutdown(); // ?
        myHandler.sendMessage(message);
    }
}

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException,
        JSONException {/*ww w . jav  a2s .  c o  m*/
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}