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:code.google.restclient.client.HitterClient.java

private MultipartEntity getMultipartEntity(ViewRequest req) throws RCException {
    MultipartEntity reqEntity = new MultipartEntity();
    Map<String, String> params = req.getParams();
    String paramValue = null;/*  w ww  . java  2s  . c o  m*/
    StringBody stringBody = null;

    try {
        for (String paramName : params.keySet()) {
            paramValue = params.get(paramName);
            stringBody = new StringBody(paramValue, Charset.forName(RCConstants.DEFAULT_CHARSET));
            reqEntity.addPart(paramName, stringBody);
        }
        String fileParamName = req.getFileParamName();
        File selectedFile = new File(req.getFilePath());

        if (selectedFile.exists() && !RCUtil.isEmpty(fileParamName)) {
            String mimeType = MimeTypeUtil.getMimeType(req.getFilePath());
            FileBody fileBody = new FileBody(selectedFile, mimeType);
            reqEntity.addPart(fileParamName, fileBody);
        }
    } catch (UnsupportedEncodingException e) {
        throw new RCException(
                "getMultipartEntity(): Could not prepare multipart entity due to unsupported encoding", e);
    }
    return reqEntity;
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (mode != null) {
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        }// w  w w. j  a  v  a 2s  .com
        for (String key : parameters.keySet()) {
            List<Object> value = parameters.get(key);
            ContentType contentType = contentTypes.get(key);
            for (Object cur : value) {
                if (cur instanceof File) {
                    File file = (File) cur;
                    builder.addPart(key, new FileBody(file, contentType, file.getName()));
                } else if (cur instanceof InputStreamBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else if (cur instanceof ByteArrayBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else {
                    builder.addPart(key, new StringBody(cur.toString(), contentType));
                }
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java

/** {@inheritDoc} */
@Override/*from   www  .  jav  a2  s. c o m*/
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}

From source file:com.hoiio.api.FaxAPI.java

/***
 * Sends a fax specified by the method parameters
 * @see <a href="http://developer.hoiio.com/docs/fax_send.html">http://developer.hoiio.com/docs/fax_send.html</a>
 * @param auth The user authorization object for the request
 * @param sender The sender number or caller id to be displayed
 * @param dest The destination to send the fax to. Phone numbers should start with a "+" and country code (E.164 format), e.g. +6511111111.
 * @param filepath The path of the fax to be sent
 * @param filename The file name of the fax desired
 * @return A unique reference ID for this fax transaction. This parameter will not be present if the request was not successful.
 * @throws HttpPostConnectionException if there is a connection failure
 * @throws HoiioRestException if there were problems using this REST API
 *///from w  w  w. ja  v  a  2s . c  o  m
public static String sendFax(HoiioAuth auth, String sender, String dest, String filepath, String filename)
        throws HttpPostConnectionException, HoiioRestException {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost method = new HttpPost(APIUrls.SEND_FAX);

        MultipartEntity entity = new MultipartEntity();

        entity.addPart("app_id", new StringBody(auth.getAppId(), Charset.forName("UTF-8")));
        entity.addPart("access_token", new StringBody(auth.getToken(), Charset.forName("UTF-8")));
        entity.addPart("dest", new StringBody(dest, Charset.forName("UTF-8")));
        entity.addPart("tag", new StringBody(filename, Charset.forName("UTF-8")));
        entity.addPart("filename", new StringBody(filename, Charset.forName("UTF-8")));
        if (sender != null && sender.length() > 0) {
            entity.addPart("caller_id", new StringBody(sender, Charset.forName("UTF-8")));
        }
        FileBody fileBody = new FileBody(new File(filepath));
        entity.addPart("file", fileBody);
        method.setEntity(entity);

        log.info("executing request " + method.getRequestLine());
        HttpResponse httpResponse = httpclient.execute(method);
        String responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
        final APIResponse response = new APIResponse(responseBody);

        if (response.getStatus() == APIStatus.success_ok) {
            return response.getResponseMap().getString("txn_ref");
        } else {
            log.error("Error with request: " + method.getRequestLine());
            log.error(response.getResponseString());
            throw new HoiioRestException(new APIRequest(APIUrls.SEND_FAX, method.getRequestLine().toString()),
                    response);
        }
    } catch (IOException ex) {
        throw new HttpPostConnectionException(ex);
    }

}

From source file:MainFrame.HttpCommunicator.java

public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException {
    String response = null;/*w  w  w . j  ava  2s.c  o 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(jsObj.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();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

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

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.removeLesson", head);

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

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:org.opendatakit.aggregate.externalservice.OhmageJsonServer.java

/**
 * Uploads a set of submissions to the ohmage system.
 *
 * @throws IOException//from   w  w w . ja  v  a2 s  . c  om
 * @throws ClientProtocolException
 * @throws ODKExternalServiceException
 * @throws URISyntaxException
 */
public void uploadSurveys(List<OhmageJsonTypes.Survey> surveys, Map<UUID, ByteArrayBody> photos,
        CallingContext cc)
        throws ClientProtocolException, IOException, ODKExternalServiceException, URISyntaxException {

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF_CHARSET);
    // emit the configured publisher parameters if the values are non-empty...
    String value;
    value = getOhmageCampaignUrn();
    if (value != null && value.length() != 0) {
        StringBody campaignUrn = new StringBody(getOhmageCampaignUrn(), UTF_CHARSET);
        reqEntity.addPart("campaign_urn", campaignUrn);
    }
    value = getOhmageCampaignCreationTimestamp();
    if (value != null && value.length() != 0) {
        StringBody campaignCreationTimestamp = new StringBody(getOhmageCampaignCreationTimestamp(),
                UTF_CHARSET);
        reqEntity.addPart("campaign_creation_timestamp", campaignCreationTimestamp);
    }
    value = getOhmageUsername();
    if (value != null && value.length() != 0) {
        StringBody user = new StringBody(getOhmageUsername(), UTF_CHARSET);
        reqEntity.addPart("user", user);
    }
    value = getOhmageHashedPassword();
    if (value != null && value.length() != 0) {
        StringBody hashedPassword = new StringBody(getOhmageHashedPassword(), UTF_CHARSET);
        reqEntity.addPart("passowrd", hashedPassword);
    }
    // emit the client identity and the json representation of the survey...
    StringBody clientParam = new StringBody(cc.getServerURL());
    reqEntity.addPart("client", clientParam);
    StringBody surveyData = new StringBody(gson.toJson(surveys));
    reqEntity.addPart("survey", surveyData);

    // emit the file streams for all the media attachments
    for (Entry<UUID, ByteArrayBody> entry : photos.entrySet()) {
        reqEntity.addPart(entry.getKey().toString(), entry.getValue());
    }

    HttpResponse response = super.sendHttpRequest(POST, getServerUrl(), reqEntity, null, cc);
    String responseString = WebUtils.readResponse(response);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
        throw new ODKExternalServiceCredentialsException(
                "failure from server: " + statusCode + " response: " + responseString);
    } else if (statusCode >= 300) {
        throw new ODKExternalServiceException(
                "failure from server: " + statusCode + " response: " + responseString);
    }
}

From source file:org.codegist.crest.HttpClientRestService.java

private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException {
    HttpUriRequest uriRequest;//from   w ww  . ja va  2s.  c  o m

    String queryString = "";
    if (request.getQueryParams() != null) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String qs = URLEncodedUtils.format(params, request.getEncoding());
        queryString = Strings.isNotBlank(qs) ? ("?" + qs) : "";
    }
    String uri = request.getUri().toString() + queryString;

    switch (request.getMeth()) {
    default:
    case GET:
        uriRequest = new HttpGet(uri);
        break;
    case POST:
        uriRequest = new HttpPost(uri);
        break;
    case PUT:
        uriRequest = new HttpPut(uri);
        break;
    case DELETE:
        uriRequest = new HttpDelete(uri);
        break;
    case HEAD:
        uriRequest = new HttpHead(uri);
        break;
    }
    if (uriRequest instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest);
        HttpEntity entity;
        if (Params.isForUpload(request.getBodyParams().values())) {
            MultipartEntity multipartEntity = new MultipartEntity();
            for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) {
                ContentBody body;
                if (param.getValue() instanceof InputStream) {
                    body = new InputStreamBody((InputStream) param.getValue(), param.getKey());
                } else if (param.getValue() instanceof File) {
                    body = new FileBody((File) param.getValue());
                } else if (param.getValue() != null) {
                    body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset());
                } else {
                    body = new StringBody(null);
                }
                multipartEntity.addPart(param.getKey(), body);
            }
            entity = multipartEntity;
        } else {
            List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size());
            for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) {
                params.add(new BasicNameValuePair(param.getKey(),
                        param.getValue() != null ? param.getValue().toString() : null));
            }
            entity = new UrlEncodedFormEntity(params, request.getEncoding());
        }

        enclosingRequestBase.setEntity(entity);
    }

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            uriRequest.setHeader(header.getKey(), header.getValue());
        }
    }

    if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) {
        HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(),
                request.getConnectionTimeout().intValue());
    }

    if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) {
        HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue());
    }

    return uriRequest;
}

From source file:com.mashape.client.http.HttpClient.java

public static <T> MashapeResponse<T> doRequest(Class<T> clazz, HttpMethod httpMethod, String url,
        Map<String, Object> parameters, ContentType contentType, ResponseType responseType,
        List<Authentication> authenticationHandlers) {
    if (authenticationHandlers == null)
        authenticationHandlers = new ArrayList<Authentication>();
    if (parameters == null)
        parameters = new HashMap<String, Object>();

    // Sanitize null parameters
    Set<String> keySet = new HashSet<String>(parameters.keySet());
    for (String key : keySet) {
        if (parameters.get(key) == null) {
            parameters.remove(key);//from  w ww .ja va  2 s. co  m
        }
    }

    List<Header> headers = new LinkedList<Header>();

    // Handle authentications
    for (Authentication authentication : authenticationHandlers) {
        if (authentication instanceof HeaderAuthentication) {
            headers.addAll(authentication.getHeaders());
        } else {
            Map<String, String> queryParameters = authentication.getQueryParameters();
            if (authentication instanceof QueryAuthentication) {
                parameters.putAll(queryParameters);
            } else if (authentication instanceof OAuth10aAuthentication) {
                if (url.endsWith("/oauth_url") == false && (queryParameters == null
                        || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null
                        || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) {
                    throw new RuntimeException(
                            "Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values");
                }
                headers.add(new BasicHeader("x-mashape-oauth-consumerkey",
                        queryParameters.get(OAuthAuthentication.CONSUMER_KEY)));
                headers.add(new BasicHeader("x-mashape-oauth-consumersecret",
                        queryParameters.get(OAuthAuthentication.CONSUMER_SECRET)));
                headers.add(new BasicHeader("x-mashape-oauth-accesstoken",
                        queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)));
                headers.add(new BasicHeader("x-mashape-oauth-accesssecret",
                        queryParameters.get(OAuthAuthentication.ACCESS_SECRET)));

            } else if (authentication instanceof OAuth2Authentication) {
                if (url.endsWith("/oauth_url") == false && (queryParameters == null
                        || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) {
                    throw new RuntimeException(
                            "Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value");
                }
                parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN));
            }
        }
    }

    headers.add(new BasicHeader("User-Agent", USER_AGENT));

    HttpUriRequest request = null;

    switch (httpMethod) {
    case GET:
        request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters));
        break;
    case POST:
        request = new HttpPost(url);
        break;
    case PUT:
        request = new HttpPut(url);
        break;
    case DELETE:
        request = new HttpDeleteWithBody(url);
        break;
    }

    for (Header header : headers) {
        request.addHeader(header);
    }

    if (httpMethod != HttpMethod.GET) {
        switch (contentType) {
        case BINARY:
            MultipartEntity entity = new MultipartEntity();
            for (Entry<String, Object> parameter : parameters.entrySet()) {
                if (parameter.getValue() instanceof File) {
                    entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue()));
                } else {
                    try {
                        entity.addPart(parameter.getKey(),
                                new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8")));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
            break;
        case FORM:
            try {
                ((HttpEntityEnclosingRequestBase) request)
                        .setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            break;
        case JSON:
            throw new RuntimeException("Not supported content type: JSON");
        }
    }

    org.apache.http.client.HttpClient client = new DefaultHttpClient();

    try {
        HttpResponse response = client.execute(request);
        MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response);
        return mashapeResponse;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCallerUtils.java

/**
 * Constructs application/form-data entity based upon the specified parameters.
 * // w  w  w. j  a va  2s .  com
 * @param formParams
 *            form parameters
 * @return request application/form-data entity for the service
 */
private static HttpEntity constructFormDataEntity(List<ExecutionFormParam> formParams) {
    MultipartEntity entity = new MultipartEntity();
    try {
        for (ExecutionFormParam formParam : formParams) {
            if (formParam.getValues() != null) {
                for (String value : formParam.getValues()) {
                    entity.addPart(formParam.getName(), new StringBody(value, Consts.UTF_8));
                }
            } else if (formParam.getFiles() != null) {
                for (FileValue fileValue : formParam.getFiles()) {
                    FileBody fileBody = new FileBody(fileValue.getFile(), fileValue.getFilename(),
                            fileValue.getMimetype(), null);
                    entity.addPart(formParam.getName(), fileBody);
                }
            } else {
                entity.addPart(formParam.getName(), new StringBody("", Consts.UTF_8));
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new WrdzRuntimeException("The encoding " + Consts.UTF_8 + " is not supported");
    }
    return entity;
}