Example usage for org.springframework.http HttpEntity HttpEntity

List of usage examples for org.springframework.http HttpEntity HttpEntity

Introduction

In this page you can find the example usage for org.springframework.http HttpEntity HttpEntity.

Prototype

public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given body and headers.

Usage

From source file:com.epl.ticketws.services.QueryService.java

public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) {

    try {//from   www.j ava2s .  c  o  m
        URI uri = new URL(url).toURI();
        long timestamp = new Date().getTime();

        HttpMethod httpMethod;
        if (method.equalsIgnoreCase("post")) {
            httpMethod = HttpMethod.POST;
        } else {
            httpMethod = HttpMethod.GET;
        }

        String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters);

        // logger.info("String to sign: " + stringToSign);
        String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license);
        // logger.info("Authorization string: " + authorization);

        // Setting Headers
        HttpHeaders headers = new HttpHeaders();
        if (accept.equalsIgnoreCase("json")) {
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        } else {
            headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        }

        headers.add("Authorization", authorization);
        headers.add("OB_DATE", "" + timestamp);
        headers.add("OB_Terminal", terminal);
        headers.add("OB_User", user);
        headers.add("OB_Channel", channel);
        headers.add("OB_POS", pos);
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<String> entity;

        if (httpMethod == HttpMethod.POST) {
            // Adding post parameters to POST body
            String parameterStringBody = getParametersAsString(parameters);
            entity = new HttpEntity<String>(parameterStringBody, headers);
            // logger.info("POST Body: " + parameterStringBody);
        } else {
            entity = new HttpEntity<String>(headers);
        }

        RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setInterceptors(interceptors);

        // Converting to UTF-8. OB Rest replies in windows charset.
        //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(UTF_8)));

        if (accept.equalsIgnoreCase("json")) {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter());
        } else {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter());
        }

        ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc);

        if (!response.getStatusCode().is2xxSuccessful())
            throw new HttpClientErrorException(response.getStatusCode());

        return response.getBody();
    } catch (HttpClientErrorException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateElectrodeLocation.java

/**
 * Method, where electrode location information is pushed to server in order to create user.
 * All heavy lifting is made here./*w  w  w. j a va2  s.  co  m*/
 *
 * @param electrodeLocations only one ElectrodeLocation object is accepted
 * @return information about created electrode location
 */
@Override
protected ElectrodeLocation doInBackground(ElectrodeLocation... electrodeLocations) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_ELECTRODE_LOCATIONS;

    setState(RUNNING, R.string.working_ws_create_electrode_location);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    requestHeaders.setContentType(MediaType.APPLICATION_XML);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    ElectrodeLocation location = electrodeLocations[0];

    try {
        Log.d(TAG, url);

        HttpEntity<ElectrodeLocation> entity = new HttpEntity<ElectrodeLocation>(location, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, ElectrodeLocation.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restSchemaDoesNotExistsTest() throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    headers.add("graphql-schema", "no-such-schema");

    GraphQLServerRequest qlQuery = new GraphQLServerRequest("{viewer{ id }}");

    HttpEntity<GraphQLServerRequest> httpEntity = new HttpEntity<>(qlQuery, headers);
    ResponseEntity<GraphQLServerResult> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + "/graphql", HttpMethod.POST, httpEntity, GraphQLServerResult.class);

    GraphQLServerResult result = responseEntity.getBody();
    Assert.assertFalse(CollectionUtils.isEmpty(result.getErrors()));
    LOGGER.info(objectMapper.writeValueAsString(result));
}

From source file:com.hatta.consumer.App.java

private static void createCustomer(User user, AuthTokenInfo tokenInfo) {
    Assert.notNull(tokenInfo, "Authenticate first please......");
    RestTemplate restTemplate = new RestTemplate();
    System.out.println("Create a customer: " + user.getName());
    HttpEntity<Object> request = new HttpEntity<Object>(user, getHeaders());
    restTemplate.postForLocation(/*w  w  w  .  j ava  2 s .co m*/
            REST_SERVICE_URI + "/api/user" + QPM_ACCESS_TOKEN + tokenInfo.getAccess_token(), request,
            User.class);
}

From source file:io.pivotal.spring.cloud.service.config.VaultTokenRenewalAutoConfiguration.java

private HttpEntity<Map<String, Long>> buildTokenRenewRequest(String vaultToken, long renewTTL) {
    Map<String, Long> requestBody = new HashMap<>();
    requestBody.put("increment", renewTTL);
    HttpHeaders headers = new HttpHeaders();
    headers.set("X-Vault-Token", vaultToken);
    HttpEntity<Map<String, Long>> request = new HttpEntity<Map<String, Long>>(requestBody, headers);
    return request;
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsDisabledPredefinedTests.java

@Test
public void basicAuthenticationServiceTest() throws Exception {
    int port = context.getEmbeddedServletContainer().getPort();

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<String> entity = new HttpEntity<String>("headers", headers);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + basicAuthenticationEndpointPath, HttpMethod.POST, entity,
            AuthorizationData.class);
    // When an enpoint is disabled, "405 - METHOD NOT ALLOWED" is returned
    assertEquals(HttpStatus.METHOD_NOT_ALLOWED, responseEntity.getStatusCode());
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

public String createOrcid(String email, String givenNames, String familyName)
        throws OrcidException, OrcidEmailExistsException, OrcidHttpException {

    String newOrcid = null;//from   ww  w  .ja v a  2  s  .c o m

    log.debug("Creating ORCID...");
    log.debug("email: " + email);
    log.debug("givenNames: " + givenNames);
    log.debug("familyName: " + familyName);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");
    headers.set("Content-Type", "application/vdn.orcid+xml");
    headers.set("Authorization", "Bearer " + orcidCreateToken);

    OrcidMessage message = new OrcidMessage();
    message.setEmail(email);
    message.setGivenNames(givenNames);
    message.setFamilyName(familyName);
    message.setMessageVersion(orcidMessageVersion);
    //TODO Affiliation should be set based on organization once faculty from more than one organization are processed
    message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT);
    message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER);
    message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER);
    message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO);
    message.setAffiliationOrganizationAddressCountry(OrcidMessage.US);
    message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER);
    message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD);

    HttpEntity entity = new HttpEntity(message, headers);

    log.debug("Configured RestTemplate Message Converters...");
    List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters();
    for (HttpMessageConverter<?> converter : converters) {
        log.debug("converter: " + converter);
        log.debug("supported media types: " + converter.getSupportedMediaTypes());
        log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(String.class, MediaType.APPLICATION_XML));
        log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML));
    }

    log.debug("Request headers: " + headers);

    HttpStatus responseStatusCode = null;
    String responseBody = null;

    try {
        if (useTestHttpProxy.equalsIgnoreCase("TRUE")) {
            log.info("Using HTTP ***TEST*** proxy...");
            System.setProperty("http.proxyHost", testHttpProxyHost);
            System.setProperty("http.proxyPort", testHttpProxyPort);
            log.info("http.proxyHost: " + System.getProperty("http.proxyHost"));
            log.info("http.proxyPort: " + System.getProperty("http.proxyPort"));
        }
        ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity,
                String.class);
        responseStatusCode = responseEntity.getStatusCode();
        responseBody = responseEntity.getBody();
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        URI locationURI = responseHeaders.getLocation();
        String uriString = locationURI.toString();
        newOrcid = extractOrcid(uriString);
        log.debug("HTTP response status code: " + responseStatusCode);
        log.debug("HTTP response headers:     " + responseHeaders);
        log.debug("HTTP response body:        " + responseBody);
        log.debug("HTTP response location:    " + locationURI);
        log.debug("New ORCID:                 " + newOrcid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
            log.debug(e.getStatusCode());
            log.debug(e.getResponseBodyAsString());
            log.debug(e.getMessage());
            throw new OrcidEmailExistsException(e);
        }
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }

    return newOrcid;
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateWeather.java

/**
 * Method, where Weather information is pushed to server in order to create user.
 * All heavy lifting is made here.//from  www  . j  a va 2 s  . c o  m
 *
 * @param weathers only one Weather object is accepted
 * @return information about created weather
 */
@Override
protected Weather doInBackground(Weather... weathers) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_WEATHER + "/" + researchGroupId;

    setState(RUNNING, R.string.working_ws_create_weather);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    requestHeaders.setContentType(MediaType.APPLICATION_XML);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Weather weather = weathers[0];

    try {
        Log.d(TAG, url);

        HttpEntity<Weather> entity = new HttpEntity<Weather>(weather, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, Weather.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.steps.AppBitsUploadingStep.java

/**
 * Prepares request to CF//w  w w  .j a va  2  s  .  c o  m
 * <a href="https://apidocs.cloudfoundry.org/225/apps/uploads_the_bits_for_an_app.html">endpoint
 * </a>
 * 
 * @param dataPath
 * @return prepared request
 * @throws IOException
 */
private HttpEntity<MultiValueMap<String, Object>> prepareMutlipartRequest(Path dataPath) throws IOException {
    HttpEntity<String> resourcesPart = prepareResourcesRequestPart();
    HttpEntity<ByteArrayResource> dataPart = prepareDataRequestPart(dataPath);

    MultiValueMap<String, Object> multiPartRequest = new LinkedMultiValueMap<>();
    multiPartRequest.add("resources", resourcesPart);
    multiPartRequest.add("application", dataPart);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    return new HttpEntity<>(multiPartRequest, headers);

}

From source file:com.marklogic.mgmt.admin.AdminManager.java

public void installAdmin(String username, String password) {
    final URI uri = adminConfig.buildUri("/admin/v1/instance-admin");

    String json = null;//ww w .j a v a  2 s .  c  o m
    if (username != null && password != null) {
        json = format("{\"admin-username\":\"%s\", \"admin-password\":\"%s\", \"realm\":\"public\"}", username,
                password);
    } else {
        json = "{}";
    }
    final String payload = json;

    logger.info("Installing admin user at: " + uri);
    invokeActionRequiringRestart(new ActionRequiringRestart() {
        @Override
        public boolean execute() {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<String>(payload, headers);
            try {
                ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, entity,
                        String.class);
                logger.info("Admin installation response: " + response);
                // According to http://docs.marklogic.com/REST/POST/admin/v1/init, a 202 is sent back in the event a
                // restart is needed. A 400 or 401 will be thrown as an error by RestTemplate.
                return HttpStatus.ACCEPTED.equals(response.getStatusCode());
            } catch (HttpClientErrorException hcee) {
                if (HttpStatus.BAD_REQUEST.equals(hcee.getStatusCode())) {
                    logger.warn("Caught 400 error, assuming admin user already installed; response body: "
                            + hcee.getResponseBodyAsString());
                    return false;
                }
                throw hcee;
            }
        }
    });
}