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:impalapayapis.ApiRequestBank.java

public String doPost() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringEntity entity;/*from   w ww  .j a  v a 2s  . co  m*/
    String out = "";

    try {
        entity = new StringEntity(params);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        HttpResponse response = httpclient.execute(httppost);

        // for debugging
        System.out.println(entity.getContentType());
        System.out.println(entity.getContentLength());
        System.out.println(EntityUtils.toString(entity));
        System.out.println(EntityUtils.toByteArray(entity).length);

        //System.out.println(           "----------------------------------------");

        System.out.println(response.getStatusLine());
        System.out.println(url);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        out = rd.readLine();
        JsonElement root = new JsonParser().parse(out);

        String specificvalue = root.getAsJsonObject().get("replace with key of the value to retrieve")
                .getAsString();
        System.out.println(specificvalue);

        /**
         * String line = ""; while ((line = rd.readLine()) != null) {
         * //System.out.println(line); }
        *
         */

    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException for URL: '" + url + "'");

        logger.error(ExceptionUtils.getStackTrace(e));
    } catch (ClientProtocolException e) {
        logger.error("ClientProtocolException for URL: '" + url + "'");
        logger.error(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        logger.error("IOException for URL: '" + url + "'");
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    return out;
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramPostRequest.java

@Override
public T execute() throws ClientProtocolException, IOException {
    HttpPost post = new HttpPost(InstagramConstants.API_URL + getUrl());
    post.addHeader("Connection", "close");
    post.addHeader("Accept", "*/*");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    post.addHeader("Cookie2", "$Version=1");
    post.addHeader("Accept-Language", "en-US");
    post.addHeader("User-Agent", InstagramConstants.USER_AGENT);

    log.debug("User-Agent: " + InstagramConstants.USER_AGENT);
    String payload = getPayload();
    log.debug("Base Payload: " + payload);

    if (isSigned()) {
        payload = InstagramHashUtil.generateSignature(payload);
    }/*from w w w . ja v  a2s  . c  om*/
    log.debug("Final Payload: " + payload);
    post.setEntity(new StringEntity(payload));

    HttpResponse response = api.getClient().execute(post);
    api.setLastResponse(response);

    int resultCode = response.getStatusLine().getStatusCode();
    String content = EntityUtils.toString(response.getEntity());

    post.releaseConnection();

    return parseResult(resultCode, content);
}

From source file:org.activiti.rest.service.api.identity.GroupMembershipResourceTest.java

public void testCreatemembership() throws Exception {
    try {//from w  ww.j  a  v a2s  . c o m
        Group testGroup = identityService.newGroup("testgroup");
        testGroup.setName("Test group");
        testGroup.setType("Test type");
        identityService.saveGroup(testGroup);

        User testUser = identityService.newUser("testuser");
        identityService.saveUser(testUser);

        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("userId", "testuser");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_GROUP_MEMBERSHIP_COLLECTION, "testgroup"));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("testuser", responseNode.get("userId").textValue());
        assertEquals("testgroup", responseNode.get("groupId").textValue());
        assertTrue(responseNode.get("url").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                RestUrls.URL_GROUP_MEMBERSHIP, testGroup.getId(), testUser.getId())));

        Group createdGroup = identityService.createGroupQuery().groupId("testgroup").singleResult();
        assertNotNull(createdGroup);
        assertEquals("Test group", createdGroup.getName());
        assertEquals("Test type", createdGroup.getType());

        assertNotNull(identityService.createUserQuery().memberOfGroup("testgroup").singleResult());
        assertEquals("testuser",
                identityService.createUserQuery().memberOfGroup("testgroup").singleResult().getId());
    } finally {
        try {
            identityService.deleteGroup("testgroup");
        } catch (Throwable ignore) {
            // Ignore, since the group may not have been created in the test
            // or already deleted
        }

        try {
            identityService.deleteUser("testuser");
        } catch (Throwable ignore) {
            // Ignore, since the group may not have been created in the test
            // or already deleted
        }
    }
}

From source file:org.fcrepo.auth.integration.AbstractResourceIT.java

protected static HttpPost postDSMethod(final String pid, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPost post = new HttpPost(serverAddress + pid + "/" + ds + "/jcr:content");
    post.setEntity(new StringEntity(content));
    return post;/*from w  w w.j  av a 2  s  . c  o  m*/
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImplTest.java

@Test
public void testRetryOnHttp503() throws Exception {
    final byte[] requestBytes = "fake_request".getBytes(UTF_8);
    final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class);
    final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class);
    final StatusLine badStatusLine = mock(StatusLine.class);
    final StatusLine goodStatusLine = mock(StatusLine.class);
    final StringEntity responseEntity = new StringEntity("success");
    final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() {
        private int iteration = 0;

        @Override/*from w  w  w .  j  a  v a  2 s.com*/
        public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable {
            iteration++;
            if (1 == iteration) {
                return badResponse;
            } else {
                return goodResponse;
            }
        }
    };

    final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);

    when(client.send(any(byte[].class))).thenCallRealMethod();
    when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed);

    when(badResponse.getStatusLine()).thenReturn(badStatusLine);
    when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE);

    when(goodResponse.getStatusLine()).thenReturn(goodStatusLine);
    when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(goodResponse.getEntity()).thenReturn(responseEntity);

    byte[] responseBytes = client.send(requestBytes);
    assertEquals("success", new String(responseBytes, UTF_8));
}

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

/**
 * Testcase for Create Specimen when CollectionProtocol is invalid
 *///from   w ww  .j  av  a2s  .c  o m
@Test
public void createSpecimenForInvalidCollectionProtocolSpecimens() {
    try {
        final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl);
        final StringEntity reqentity = new StringEntity(getInsertInvalidCollectionProtocolXMLStr());
        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("<errorCode>1101</errorCode>"));
        }
    } catch (ClientProtocolException e) {
        Assert.fail(e.getMessage());
    } catch (IllegalStateException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.apache.aurora.scheduler.events.Webhook.java

private HttpPost createPostRequest(TaskStateChange stateChange) throws UnsupportedEncodingException {
    String eventJson = stateChange.toJson();
    HttpPost post = new HttpPost();
    post.setURI(webhookInfo.getTargetURI());
    post.setHeader("Timestamp", Long.toString(Instant.now().toEpochMilli()));
    post.setEntity(new StringEntity(eventJson));
    webhookInfo.getHeaders().entrySet().forEach(e -> post.setHeader(e.getKey(), e.getValue()));
    return post;//from w ww.j  a  v a 2  s .  co  m
}

From source file:org.apache.camel.component.restlet.RestletPostContentTest.java

@Test
public void testPostBody() throws Exception {
    HttpUriRequest method = new HttpPost("http://localhost:" + portNum + "/users/homer");
    ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(MSG_BODY));

    HttpResponse response = doExecute(method);

    assertHttpResponse(response, 200, "text/plain");
}

From source file:com.lexicalintelligence.action.extract.BatchExtractRequest.java

@SuppressWarnings("unchecked")
public List<ExtractResponse> execute() {
    HttpPost post = new HttpPost(client.getUrl() + PATH);
    Reader reader = null;/*from   ww  w.  ja va  2 s .  c  o m*/
    try {
        StringEntity postingString = new StringEntity(gson.toJson(params));
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        //post.setHeader("Accept", "application/json");
        //post.setHeader("X-Stream", "true");
        //System.out.println(gson.toJson(params));
        //post.setEntity(new UrlEncodedFormEntity(params.values()));
        HttpResponse response = client.getHttpClient().execute(post);
        //System.out.println(">> " + IOUtils.toString(response.getEntity().getContent()));

        reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8);

        List<Map<String, Object>> result = client.getObjectMapper().readValue(reader,
                new TypeReference<List<Map<String, Object>>>() {
                });

        return result.stream().map(r -> {
            ExtractResponse extractResponse = new ExtractResponse();
            extractResponse.setId((String) r.get("id"));
            extractResponse.setEntries((Map<String, List<LexicalEntry>>) r.get("entries"));
            return extractResponse;
        }).collect(Collectors.toList());
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
    return Collections.emptyList();
}

From source file:su.fmi.photoshareclient.remote.LoginHandler.java

public static boolean register(String username, char[] password) {
    try {//from  w w w  . j  a  v  a 2  s  .c  o  m
        Random randomGenerator = new Random();
        ProjectProperties properties = new ProjectProperties();
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/create");
        StringEntity input = new StringEntity("{\"firstName\":\"desktopUser\",\"lastName\":\"desktopUserLast\","
                + "\"username\": \"" + username + "\", \"email\": \"res" + randomGenerator.nextInt()
                + "@example.com\"," + "\"password\": \"" + new String(password) + "\"}");
        input.setContentType("application/json");
        post.setEntity(input);
        HttpResponse response = (HttpResponse) client.execute(post);
        return true;
        //                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        //                String line = "";
        //                while ((line = rd.readLine()) != null) {
        //                    System.out.println(line);
        //                }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}