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) throws UnsupportedEncodingException 

Source Link

Usage

From source file:gov.nih.nci.caxchange.messaging.AdverseEventIntegrationTest.java

/**
 * TestCase for Creating Adverse Event in caAERS
 *//*ww w. j a v  a 2 s  .  c  o m*/
@Test
public void createAdverseEvent() {
    try {
        final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl);
        final StringEntity reqentity = new StringEntity(getCreateAdverseEventXMLStr());
        httppost.setEntity(reqentity);
        httppost.setHeader(HttpHeaders.CONTENT_TYPE, XMLTEXT);

        final HttpResponse response = httpclient.execute(httppost);
        final HttpEntity entity = response.getEntity();

        String createdXML = null;

        if (entity != null) {
            createdXML = EntityUtils.toString(entity);
            Assert.assertEquals(true, createdXML.contains("<responseStatus>SUCCESS</responseStatus>"));
        }
    } catch (ClientProtocolException e) {
        Assert.fail(e.getMessage());
    } catch (IllegalStateException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:io.undertow.server.handlers.AllowedMethodsTestCase.java

@Test
public void testAllowedMethods() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*from   w  w w .  j  a  va2  s .  co  m*/
        final AllowedMethodsHandler handler = new AllowedMethodsHandler(ResponseCodeHandler.HANDLE_200,
                Methods.POST);
        DefaultServer.setRootHandler(handler);

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.METHOD_NOT_ALLOWED, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        post.setEntity(new StringEntity("foo"));
        result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:tech.beshu.ror.integration.FiltersAndFieldsSecurityTests.java

private static void insertDoc(String docName, RestClient restClient, String idx, String field) {
    if (adminClient == null) {
        adminClient = restClient;/* w w  w . j a  v a  2 s .c  o m*/
    }

    String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random());
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setEntity(new StringEntity("{\"" + field + "\": \"" + docName + "\", \"dummy\": true}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:org.openmidaas.library.common.network.AndroidNetworkTransport.java

@Override
public void doPostRequest(boolean withSSL, String url, HashMap<String, String> headers, JSONObject data,
        AsyncHttpResponseHandler responseHandler) {
    try {/* ww  w .  j  a  v  a  2 s . c o m*/
        AsyncHttpClient client = new AsyncHttpClient();
        if (headers != null) {
            if (headers.size() > 0) {
                MIDaaS.logDebug(TAG, "Headers: ");
                MIDaaS.logDebug(TAG, "Key: Value");
                for (String key : headers.keySet()) {
                    client.addHeader(key, headers.get(key));
                    MIDaaS.logDebug(TAG, "" + key + " : " + headers.get(key));
                }
            }
        }
        MIDaaS.logDebug(TAG, "Data: " + data.toString());
        client.post(null, mHostUrl + url, new StringEntity(data.toString()), "application/json",
                responseHandler);
    } catch (UnsupportedEncodingException e) {
        MIDaaS.logError(TAG, e.getMessage());
        responseHandler.onFailure(e, e.getMessage());
    }
}

From source file:org.activiti.rest.service.api.runtime.SignalsResourceTest.java

@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml" })
public void testSignalEventReceivedSync() throws Exception {

    org.activiti.engine.repository.Deployment tenantDeployment = repositoryService.createDeployment()
            .addClasspathResource(/*from   w ww  .j a  v a2 s  .c  o  m*/
                    "org/activiti/rest/service/api/runtime/SignalsResourceTest.process-signal-start.bpmn20.xml")
            .tenantId("my tenant").deploy();

    try {

        // Signal without vars, without tenant
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("signalName", "The Signal");

        HttpPost httpPost = new HttpPost(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_SIGNALS));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal without
        // tenant ID set
        assertEquals(1, runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId()
                .processDefinitionKey("processWithSignalStart1").count());

        // Signal with tenant
        requestNode.put("tenantId", "my tenant");
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal, in the
        // right tenant
        assertEquals(1, runtimeService.createProcessInstanceQuery().processInstanceTenantId("my tenant")
                .processDefinitionKey("processWithSignalStart1").count());

        // Signal with tenant AND variables
        ArrayNode vars = requestNode.putArray("variables");
        ObjectNode var = vars.addObject();
        var.put("name", "testVar");
        var.put("value", "test");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal, in the
        // right tenant and with var set
        assertEquals(1,
                runtimeService.createProcessInstanceQuery().processInstanceTenantId("my tenant")
                        .processDefinitionKey("processWithSignalStart1").variableValueEquals("testVar", "test")
                        .count());

        // Signal without tenant AND variables
        requestNode.remove("tenantId");

        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_NO_CONTENT));

        // Check if process is started as a result of the signal, witout
        // tenant and with var set
        assertEquals(1,
                runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId()
                        .processDefinitionKey("processWithSignalStart1").variableValueEquals("testVar", "test")
                        .count());

    } finally {
        // Clean up tenant-specific deployment
        if (tenantDeployment != null) {
            repositoryService.deleteDeployment(tenantDeployment.getId(), true);
        }
    }
}

From source file:org.flowable.rest.dmn.service.api.decision.DmnRuleServiceResourceTest.java

@DmnDeploymentAnnotation(resources = { "org/flowable/rest/dmn/service/api/decision/multi-hit.dmn" })
public void testExecutionDecision() throws Exception {
    // Add decision key
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("decisionKey", "decision1");

    // add input variable
    ArrayNode variablesNode = objectMapper.createArrayNode();
    ObjectNode variableNode = objectMapper.createObjectNode();
    variableNode.put("name", "inputVariable1");
    variableNode.put("type", "integer");
    variableNode.put("value", 5);
    variablesNode.add(variableNode);//from w ww . java  2  s . c  o  m

    requestNode.set("inputVariables", variablesNode);

    HttpPost httpPost = new HttpPost(
            SERVER_URL_PREFIX + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_RULE_SERVICE_EXECUTE));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

    // Check response
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);

    ArrayNode resultVariables = (ArrayNode) responseNode.get("resultVariables");

    assertEquals(3, resultVariables.size());
}

From source file:asterixUpdateClient.AsterixUpdateClientUtility.java

@Override
public void executeUpdate(int qid, Update update) {
    long rspTime = Constants.INVALID_TIME;
    String updateBody = null;// www.ja va2 s  .  com
    HttpResponse response;
    try {
        updateBody = ((AqlUpdate) update).printAqlStatement();
        httpPost.setEntity(new StringEntity(updateBody));

        long s = System.currentTimeMillis();
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
        long e = System.currentTimeMillis();
        rspTime = (e - s);
    } catch (Exception e) {
        System.err.println("Problem in running update " + qid + " against Asterixdb !");
        updateStat(qid, 0, Constants.INVALID_TIME);
        return;
    }

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Update " + qid + " against Asterixdb returned http error code");
        rspTime = Constants.INVALID_TIME;
    }
    updateStat(qid, 0, rspTime);

    if (++counter % TRACE_PACE == 0) {
        System.out.println(
                counter + " Updates done - last one took\t" + rspTime + " ms\tStatus-Code\t" + statusCode);
    }

}

From source file:requestToApi.java

public String addHomeServer(String serverName, String userId) {
    String output2 = "";
    try {/*from  w ww  . ja  v  a 2 s. com*/

        StringEntity input = new StringEntity(
                "{\"serverName\":\"" + serverName + "\",\"userId\":\"" + userId + "\"}");
        String URL = "http://smarthomeinterface.azurewebsites.net/addHomeServer";
        output2 = send(input, URL);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output2;
}

From source file:com.alta189.deskbin.services.paste.HastebinService.java

@Override
public String paste(String content, boolean isPrivate) throws PasteException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(URL);
    try {//from w  ww.j  a va  2  s .c  om
        post.setEntity(new StringEntity(content));
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return "http://hastebin.com/" + new JSONObject(result).getString("key");
    } catch (UnsupportedEncodingException e) {
        throw new PasteException(e);
    } catch (ClientProtocolException e) {
        throw new PasteException(e);
    } catch (IOException e) {
        throw new PasteException(e);
    } catch (JSONException e) {
        throw new PasteException(e);
    }
}

From source file:org.openbmap.unifiedNlp.services.JSONParser.java

/**
 * Sends a http post request/* ww  w .  j  a  v a2s.  c  o m*/
 *
 * @param url JSON endpoint
 * @param params JSON parameters
 * @return server reply
 */
public JSONObject getJSONFromUrl(String url, JSONObject params) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        //passes the results to a string builder/entity
        StringEntity se = new StringEntity(params.toString());

        //sets the post request as the resulting string
        httpPost.setEntity(se);
        //sets a request header so the page receving the request
        //will know what to do with it
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", USER_AGENT);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e(TAG, "Error converting result " + e.toString());
        }

        try {
            httpEntity.consumeContent();
        } catch (IOException e) {
            Log.e(TAG, "Error closing http entity");
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}