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(MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given headers and no body.

Usage

From source file:com.cloudera.nav.plugin.client.NavApiCient.java

/**
 * Call the Navigator API and retrieve all available sources
 *
 * @return a collection of available sources
 *//*  w w w.j a  v a 2  s.  c o  m*/
public Collection<Source> getAllSources() {
    RestTemplate restTemplate = new RestTemplate();
    String url = getSourceUrl();
    HttpHeaders headers = getAuthHeaders();
    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<SourceAttrs[]> response = restTemplate.exchange(url, HttpMethod.GET, request,
            SourceAttrs[].class);
    Collection<Source> sources = Lists.newArrayList();
    for (SourceAttrs info : response.getBody()) {
        sources.add(info.createSource());
    }
    return sources;
}

From source file:at.create.android.ffc.http.FormBasedAuthentication.java

/**
 * Authentication via username and password.
 * @return True if the authentication succeeded, otherwise false is returned.
 *//*  ww  w .  j  a  v a  2s  .  c om*/
public boolean authenticate() {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("authentication[username]", username);
    formData.add("authentication[password]", password);
    formData.add("authentication[remember_me]", "1");

    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.postForLocation(getUrl(), formData);

    if (CookiePreserveHttpRequestInterceptor.getInstance().hasCookieWithName("user_credentials")) {
        return true;
        // Try with another method
    } else {
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(baseUri, HttpMethod.GET, requestEntity,
                String.class);

        return !responseEntity.getBody().toString().contains("authentication[username]");
    }
}

From source file:com.tservice.Logica.PersistenceFacede.java

public void realizarPago(Licencias licencia, InformacionPago pago) throws tserviceExceptions, Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<>(headers);
    String url = "http://serviciosrest.cloudhub.io/rest/PAYPAL/pago/tarjeta/" + pago.getNumeroTarjeta() + "/"
            + pago.getNombreTarjeta() + "/Credito/" + pago.getCodigoSeguridad() + "/"
            + usuarioactivo.getCorreo() + "/monto/" + (int) licencia.getValor()
            + "/seguridad/2/TService?servicio=pago";
    //http://serviciosrest.cloudhub.io/rest/PAYPAL/pago/tarjeta/4916701440291035/Visa/Credito/9209/asd@asd.com/monto/1000/seguridad/2/TService?api=api2
    ResponseEntity<Object> resultado = rest.exchange(url, HttpMethod.PUT, HttpEntity.EMPTY, Object.class);
    //http://serviciosrest.cloudhub.io/rest/PAYPAL/pago/tarjeta/4916701440291035/Visa/Credito/9209/asd@asd.com/monto/30/seguridad/2/TService?servicio=pago
    String resu = resultado.getBody().toString();

    resu = resu.replace("{", "");
    resu = resu.replace("}", "");

    ResultadoTransaccion result = new ResultadoTransaccion(resu.split(",")[0].split("=")[1],
            Integer.parseInt(resu.split(",")[1].split("=")[1]));

    if (result.getCodTransaccion() == 0) {
        throw new tserviceExceptions("La tarjeta es invalida o el saldo es insuficiente por favor verifique");
    } else/*from w w w  .  j  av a2 s.c o  m*/
        resultadoTransaccion(result.getCodTransaccion(), licencia);
}

From source file:com.github.ffremont.microservices.springboot.manager.nexus.NexusClientApiTest.java

@Test
public void testGetData() {
    String g = "gg", a = "aa", v = "1.0.0", c = "cc", p = "jar";

    // init mock/*from ww w . jav  a  2  s  .co  m*/
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.parseMediaType(MediaType.APPLICATION_JSON.toString())));
    HttpEntity<NexusDataResult> entity = new HttpEntity<>(headers);
    NexusDataResult nexusResult = new NexusDataResult();
    nexusResult.setData(new NexusData());
    ResponseEntity responseEntity = new ResponseEntity(nexusResult, HttpStatus.OK);
    when(this.nexusRestTemplate
            .exchange(prop.getBaseurl() + "/service/local/artifact/maven/resolve?r=snapshots&g=" + g + "&a=" + a
                    + "&v=" + v + "&p=" + p + "&c=" + c, HttpMethod.GET, entity, NexusDataResult.class))
                            .thenReturn(responseEntity);

    NexusData r = nexus.getData(g, a, p, c, v);

    assertNotNull(r);
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.MvcExceptionHandlerTests.java

@Test
public void test() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();//w  w w.j a va  2 s .c o  m
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    // Calling protected resource - requires CSRF token
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + "/hello")
            .queryParam(DEFAULT_CSRF_PARAMETER_NAME, loginInfo.getXsrfToken());
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.GET, entity, String.class);

    String data = responseEntity.getBody();
    assertEquals("Hello World!", data);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}

From source file:com.tce.oauth2.spring.client.services.TodoService.java

public List<Todo> findByUsername(String accessToken, String username) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + accessToken);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<Todo[]> response = restTemplate.exchange(
            OAUTH_RESOURCE_SERVER_URL + "/rest/todos/" + username, HttpMethod.GET, entity, Todo[].class);
    Todo[] todos = response.getBody();//from   w ww .  j  av a  2 s .  c  o  m

    return Arrays.asList(todos);
}

From source file:org.starfishrespect.myconsumption.android.tasks.GCMRegister.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>//from w  w w . j  a  v a 2  s. c  om
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
public void registerInBackground(final Context context) {
    AsyncTask<Void, List, String> task = new AsyncTask<Void, List, String>() {
        @Override
        protected String doInBackground(Void... params) {
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<String> responseEnt;
            template.getMessageConverters().add(new FormHttpMessageConverter());
            template.getMessageConverters().add(new StringHttpMessageConverter());
            String msg = "";

            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                String regid = gcm.register(Config.SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // Send the registration ID to the server
                String url = SingleInstance.getServerUrl() + "notifs/"
                        + SingleInstance.getUserController().getUser().getName() + "/id/" + regid;

                responseEnt = template.exchange(url, HttpMethod.POST, new HttpEntity<>(httpHeaders),
                        String.class);
                SimpleResponseDTO response = new ObjectMapper().readValue(responseEnt.getBody(),
                        SimpleResponseDTO.class);

                if (response.getStatus() != SimpleResponseDTO.STATUS_SUCCESS) {
                    msg = "Error: " + response.getStatus() + " Cannot post register id on server side.";
                }

                // Persist the registration ID - no need to register again.
                PrefUtils.setRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error:" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            LOGI(TAG, msg);
        }
    };

    task.execute();
}

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

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void listAllCustomers(AuthTokenInfo tokenInfo) {

    Assert.notNull(tokenInfo, "Authenticate first please......");

    RestTemplate restTemplate = new RestTemplate();
    ///*from  w  w w . j  a  v a 2s . c o m*/
    //        HttpHeaders headers = new HttpHeaders();
    //        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<String> request = new HttpEntity<String>(getHeaders());
    ResponseEntity<List> response = restTemplate.exchange(
            REST_SERVICE_URI + "/api/user" + QPM_ACCESS_TOKEN + tokenInfo.getAccess_token(), HttpMethod.GET,
            request, List.class);
    List<LinkedHashMap<String, Object>> customerMap = (List<LinkedHashMap<String, Object>>) response.getBody();
    //         
    //        List<LinkedHashMap<String, Object>> customerMap = restTemplate.getForObject(REST_SERVICE_URI + "/api/user", List.class);

    if (customerMap != null) {
        System.out.println("Retrieve all customers:");
        for (LinkedHashMap<String, Object> map : customerMap) {
            System.out.println("Customer : id=" + map.get("id") + ", Name=" + map.get("name") + ", Address="
                    + map.get("email") + ", Email=" + map.get("password") + map.get("enabled"));
        }
    } else {
        System.out.println("No customer exist----------");
    }
}

From source file:org.mimacom.sample.integration.patterns.user.service.integration.BulkHeadedSearchServiceIntegration.java

public void indexUserSlow(User user, int waitTime, Consumer<Void> successConsumer,
        Consumer<Throwable> failureConsumer) {
    LOG.info("[SLOW!] going to send request to index user '{}' '{}'", user.getFirstName(), user.getLastName());

    HttpEntity<User> requestEntity = new HttpEntity<>(user);
    ListenableFuture<ResponseEntity<String>> listenableFuture = this.asyncIndexRestTemplate.postForEntity(
            this.searchServiceUrl + "/index?waitTime={waitTime}", requestEntity, String.class, waitTime);

    listenableFuture.addCallback(result -> {
        LOG.info("[SLOW!] user '{}' '{}' was indexed and response status code was '{}'", user.getFirstName(),
                user.getLastName(), result.getStatusCode());
        successConsumer.accept(null);/*from   w w  w .  j  a v  a2 s.c o m*/
    }, failureConsumer::accept);
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.HttpCommunicationTest.java

private HttpEntity<String> createExpectedSimpleJsonRequest() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", "application/json");
    headers.add("Content-type", "application/json");

    return new HttpEntity<>(headers);
}