Example usage for org.apache.http.entity StringEntity StringEntity

List of usage examples for org.apache.http.entity StringEntity StringEntity

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity StringEntity.

Prototype

public StringEntity(String str, Charset charset) 

Source Link

Usage

From source file:com.redhat.refarch.microservices.warehouse.service.WarehouseService.java

public void fulfillOrder(Result result) throws Exception {

    HttpClient client = new DefaultHttpClient();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("status", "Shipped");

    URIBuilder uriBuilder = new URIBuilder("http://gateway-service:9091/customers/" + result.getCustomerId()
            + "/orders/" + result.getOrderNumber());
    HttpPatch patch = new HttpPatch(uriBuilder.build());
    patch.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
    logInfo("Executing " + patch);
    HttpResponse response = client.execute(patch);
    String responseString = EntityUtils.toString(response.getEntity());
    logInfo("Got response " + responseString);
}

From source file:org.camunda.connect.plugin.MockHttpConnectorConfigurator.java

public void configure(HttpConnector connecor) {
    connecor.addRequestInterceptor(new ConnectorRequestInterceptor() {

        public Object handleInvocation(ConnectorInvocation invocation) throws Exception {

            // intercept the call. => do not call invocation.proceed()

            // Could do validation on the invocation here:
            // invocation.getRequest() ....

            // build response using http client api...
            TestHttpResonse testHttpResonse = new TestHttpResonse();
            testHttpResonse.setEntity(new StringEntity("{...}", ContentType.APPLICATION_JSON));

            // return the response
            return new HttpResponseImpl(testHttpResonse);
        }// www  .j  ava2 s.  c  o  m
    });
}

From source file:com.macrossx.wechat.impl.WechatMessageHelper.java

@Override
public Optional<WecahtMessageTemplateRespObj> sendTemplate(WechatMessageTemplate template) {
    try {/*from  w w w  . j ava2  s . c om*/
        Optional<WechatAccessToken> token = wechatHelper.getAccessToken();
        if (token.isPresent()) {
            WechatAccessToken accessToken = token.get();
            HttpPost httpPost = new HttpPost();
            System.out.println(new Gson().toJson(template));
            httpPost.setEntity(new StringEntity(new Gson().toJson(template), "utf-8"));
            httpPost.setURI(new URI(MessageFormat.format(WechatConstants.MESSAGE_TEMPLATE_SEND_URL,
                    accessToken.getAccess_token())));
            return new WechatHttpClient().send(httpPost, WecahtMessageTemplateRespObj.class);
        }
    } catch (URISyntaxException e) {
        log.info(e.getMessage());
    }
    return Optional.empty();
}

From source file:language_engine.HttpUtils.java

public static String doHttpPost(String url, String xmlBody, Header[] headers) {
    try {//from   w  w  w  .  j ava2s. c  om
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeaders(headers);
        httpPost.setEntity(new StringEntity(xmlBody, "UTF-8"));
        HttpResponse resp = httpClient.execute(httpPost);
        return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.hybris.platform.mpintgproductcockpit.productcockpit.util.HttpInvoker.java

public String post(final String reqURL, final String reqStr, final String charset, final int timeout) {
    // Prepare HTTP post
    final HttpPost post = new HttpPost(reqURL);
    post.setHeader("Content-Type", "application/json");

    // set content type as json and charset
    final StringEntity reqEntity = new StringEntity(reqStr, ContentType.create("application/json", charset));
    post.setEntity(reqEntity);/*from  w  w  w.  j  a v a2s.c  o  m*/

    // Create HTTP client
    final HttpClient httpClient = new DefaultHttpClient();

    // set connection over time
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(timeout / 2));
    // set data loading over time
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(timeout / 2));

    // Execute request
    try {
        final HttpResponse response = httpClient.execute(post);
        // get response and return as String
        final HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity);
    } catch (final Exception e) {
        return null;
    } finally {
        post.releaseConnection();
    }
}

From source file:com.facebook.stetho.server.SecureHttpRequestHandler.java

@Override
@SuppressLint("LogMethodNoExceptionInCatch")
public final void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    try {/* ww  w  .  j a  va2  s. co  m*/
        ensureSecureRequest(request, context);
        handleSecured(request, response, context);
    } catch (PeerAuthorizationException e) {
        LogUtil.e("Unauthorized request: " + e.getMessage());
        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        response.setEntity(new StringEntity(e.getMessage() + "\n", Utf8Charset.NAME));
    }
}

From source file:com.thed.zephyr.jenkins.utils.rest.Cycle.java

public static Long createCycle(ZephyrConfigModel zephyrData) {

    Long cycleId = 0L;/*  w ww.ja  va  2  s.  c  o  m*/

    HttpResponse response = null;
    try {
        String createCycleURL = URL_CREATE_CYCLES.replace("{SERVER}", zephyrData.getRestClient().getUrl());

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("E dd, yyyy hh:mm a");
        String dateFormatForCycleCreation = sdf.format(date);

        JSONObject jObject = new JSONObject();
        String cycleName = zephyrData.getCyclePrefix() + dateFormatForCycleCreation;

        SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MMM/yy");
        String startDate = sdf1.format(date);

        GregorianCalendar gCal = new GregorianCalendar();

        if (zephyrData.getCycleDuration().trim().equalsIgnoreCase("30 days")) {
            gCal.add(Calendar.DAY_OF_MONTH, +29);
        } else if (zephyrData.getCycleDuration().trim().equalsIgnoreCase("7 days")) {
            gCal.add(Calendar.DAY_OF_MONTH, +6);
        }

        String endDate = sdf1.format(gCal.getTime());

        jObject.put("name", cycleName);
        jObject.put("projectId", zephyrData.getZephyrProjectId());
        jObject.put("versionId", zephyrData.getVersionId());
        jObject.put("startDate", startDate);
        jObject.put("endDate", endDate);

        StringEntity se = new StringEntity(jObject.toString(), "utf-8");

        HttpPost createCycleRequest = new HttpPost(createCycleURL);

        createCycleRequest.setHeader("Content-Type", "application/json");
        createCycleRequest.setEntity(se);
        response = zephyrData.getRestClient().getHttpclient().execute(createCycleRequest,
                zephyrData.getRestClient().getContext());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

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

    if (statusCode >= 200 && statusCode < 300) {
        HttpEntity entity = response.getEntity();
        String string = null;
        try {
            string = EntityUtils.toString(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            JSONObject cycleObj = new JSONObject(string);
            cycleId = cycleObj.getLong("id");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } else if (statusCode == 405) {

        try {
            throw new ClientProtocolException("ZAPI plugin license is invalid" + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }

    } else {
        try {
            throw new ClientProtocolException("Unexpected response status: " + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

    return cycleId;
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the POST way.</p>
 * /*from ww w.ja v a 2 s . c  o m*/
 * @param url      request URI
 * @param json      request parameter(json format string)
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String post(String url, String json, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    String result = null;
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;

    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "text/plain");
        httpPost.setEntity(new StringEntity(json, "UTF-8"));

        httpResponse = httpClient.execute(httpPost);

        HttpEntity entity = httpResponse.getEntity();

        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("POST?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static String sendPost2(String operation, String body) throws Exception {
    //   System.out.println ("body "+body);
    String url = "http://api.cortical.io/rest/" + operation + "?retina_name=en_associative";

    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);
    post.setHeader("api-key", "0e30f600-7b62-11e6-a057-97f4c970893c");
    post.setHeader("content-type", "application/json");
    //   post.setHeader("api-key","0e30f600-7b62-11e6-a057-97f4c970893c");
    //post.setHeader("charset", "utf-8");
    StringEntity params = new StringEntity(body, Charset.defaultCharset());
    //List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //urlParameters.add(new BasicNameValuePair("body", body));
    //urlParameters.add(new BasicNameValuePair("retina_name","en_associative"));
    /*urlParameters.add(new BasicNameValuePair("locale", ""));
    urlParameters.add(new BasicNameValuePair("caller", ""));
    urlParameters.add(new BasicNameValuePair("num", "12345"));*/

    post.setEntity(params);//from w  w w  .  ja  va2 s  .  c  om
    //  post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    // System.out.println("\nSending 'POST' request to URL : " + url);
    // System.out.println("Post parameters : " + post.getEntity());
    // System.out.println("Response Code : "
    //     + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    //  System.out.println(result.toString());
    int code = response.getStatusLine().getStatusCode();
    if (400 == code) {
        return "{\"overlappingAll\":0 , \"weightedScoring\": 0 } ";
    } else {
        return result.toString();
    }
}