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:de.codecentric.boot.admin.services.ApplicationRegistratorTest.java

@SuppressWarnings("rawtypes")
@Test/* w  ww. jav a  2s. c om*/
public void register_multiple() {
    adminProps.setRegisterOnce(false);

    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class)))
            .thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED));

    assertTrue(registrator.register());

    verify(restTemplate).postForEntity("http://sba:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);

    verify(restTemplate).postForEntity("http://sba2:8080/api/applications",
            new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health")
                    .withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080")
                    .build(), headers),
            Map.class);
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

private ResponseEntity<Driver> createOneDriver() {
    HttpHeaders headers = this.getHeaders("myusername" + ":" + "mypwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(DriverFixtures.standardDriverJSON(), headers);

    ResponseEntity<Driver> entity = template.postForEntity(
            "http://localhost:8085/xacml/populators/dvla/driveradd", requestEntity, Driver.class);
    return entity;
}

From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java

private void sendBytes(byte[] bytes, long page) {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", auth);
    requestHeaders.set("Content-Length", bytes.length + "");
    String dataUrl = url + this.tunnelInfo.get("path_in") + "/" + page;
    HttpEntity<byte[]> requestEntity = new HttpEntity<byte[]>(bytes, requestHeaders);
    if (logger.isTraceEnabled()) {
        logger.trace("SENDING: " + printBytes(bytes));
    }//w w  w.j ava2s . com
    ResponseEntity<?> response = restOperations.exchange(dataUrl, HttpMethod.PUT, requestEntity, null);
    if (logger.isDebugEnabled()) {
        logger.debug(
                "[" + bytes.length + " bytes] PUT to " + dataUrl + " resulted in: " + response.getStatusCode());
    }
}

From source file:com.athina.queue.manager.entity.HttpJob.java

@Override
public void run() {
    HttpHeaders httpHeaders = new HttpHeaders();
    headers.forEach(httpHeaders::add);//from   ww  w . ja  v  a 2  s  .  co  m
    HttpEntity<String> request = new HttpEntity<>(body, httpHeaders);
    ResponseEntity<String> response = restTemplate.exchange(url.toString(), method, request, String.class);
    int code = response.getStatusCode().value();
    String responseBody = response.getBody();
    LOG.info("{}", new HttpAuditRecord(this, code, responseBody));
}

From source file:com.atwelm.aezwidget.responses.interfaces.AEZCell.java

/**
 * Executes the URL and associated details for the cell
 * @param callback The callback when completed
 *///from   w  w w.  java 2 s.  c om
public final void execute(final ExecutionResponseCallback callback) {
    if (!isExecutable()) {
        return;
    }

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String executionType = getExecutionType();
                String executionUrl = getExecutionUrl();
                String executionBody = getExecutionBody();
                HttpHeaders executionHeaders = getExecutionHeaders();

                HttpEntity<String> requestEntity = new HttpEntity<String>(executionBody, executionHeaders);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<GenericExecutionResponse> responseEntity = restTemplate.exchange(executionUrl,
                        HttpMethod.valueOf(executionType), requestEntity, GenericExecutionResponse.class);

                int returnStatus = responseEntity.getStatusCode().value();

                if (returnStatus <= 200 && returnStatus < 300) {
                    GenericExecutionResponse response = responseEntity.getBody();
                    if (callback != null) {
                        callback.success(response);
                    }
                } else {
                    if (callback != null) {
                        callback.failure(returnStatus);
                    }
                }

            } catch (HttpStatusCodeException hsce) {
                callback.failure(hsce.getStatusCode().value());
            } catch (RestClientException rce) {
                // TODO: Make this more specific since it includes scenarios such as when the network cannot be reached
                callback.failure(-1);
            }
        }
    });
    t.start();
}

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

/**
 * Method, where scenario information is pushed to server in order to new scenario.
 * All heavy lifting is made here.//from   ww  w .j  a va2s.c  o m
 *
 * @param scenarios only one scenario is accepted - scenario to be uploaded
 * @return scenario stored
 */
@Override
protected Scenario doInBackground(Scenario... scenarios) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_SCENARIOS;

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

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    //so files wont buffer in memory
    factory.setBufferRequestBody(false);
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Scenario scenario = scenarios[0];

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(scenario.getFilePath());

        //due to multipart file, MultiValueMap is the simplest approach for performing the post request
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("scenarioName", scenario.getScenarioName());
        form.add("researchGroupId", scenario.getResearchGroupId());
        form.add("description", scenario.getDescription());
        form.add("mimeType", scenario.getMimeType());
        form.add("private", Boolean.toString(scenario.isPrivate()));
        form.add("file", toBeUploadedFile);

        HttpEntity<Object> entity = new HttpEntity<Object>(form, requestHeaders);
        // Make the network request
        ResponseEntity<Scenario> response = restTemplate.postForEntity(url, entity, Scenario.class);
        return response.getBody();
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.openbaton.common.vnfm_sdk.rest.VnfmRestHelper.java

private String post(String path, String json) {
    HttpEntity<String> requestEntity = new HttpEntity<>(json, headers);
    log.debug("url is: " + url + path);
    log.debug("BODY is: " + json);
    ResponseEntity<String> responseEntity = rest.postForEntity(url + path, requestEntity, String.class);
    this.setStatus(responseEntity.getStatusCode());
    return responseEntity.getBody();
}

From source file:org.obiba.mica.core.service.MailService.java

private synchronized void sendEmail(String subject, String templateName, Map<String, String> context,
        String recipient) {/*from  ww w .  ja v a2  s.com*/
    try {
        RestTemplate template = newRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(APPLICATION_AUTH_HEADER, getApplicationAuth());
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        StringBuilder form = new StringBuilder(Strings.isNullOrEmpty(recipient) ? "" : recipient + "&");
        form.append("subject=").append(encode(subject, "UTF-8")).append("&template=")
                .append(encode(templateName, "UTF-8"));
        context.forEach((k, v) -> {
            try {
                form.append("&").append(k).append("=").append(encode(v, "UTF-8"));
            } catch (UnsupportedEncodingException ignored) {
            }
        });
        HttpEntity<String> entity = new HttpEntity<>(form.toString(), headers);

        ResponseEntity<String> response = template.exchange(getNotificationsUrl(), HttpMethod.POST, entity,
                String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("Email sent via Agate");
        } else {
            log.error("Sending email via Agate failed with status: {}", response.getStatusCode());
        }
    } catch (Exception e) {
        log.error("Agate connection failure: {}", e.getMessage());
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.VmcScimUserEndpointIntegrationTests.java

@Test
public void userInfoSucceeds() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", "*/*");
    RestOperations client = serverRunning.getRestTemplate();
    ResponseEntity<Void> result = client.exchange(serverRunning.getUrl("/userinfo"), HttpMethod.GET,
            new HttpEntity<Void>(null, headers), null, joe.getId());
    assertEquals(HttpStatus.OK, result.getStatusCode());

}

From source file:aiai.ai.station.LaunchpadRequester.java

/**
 * this scheduler is being run at the station side
 *
 * long fixedDelay()/*from   w ww  .j  a va2 s .c  o m*/
 * Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
 */
public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;
    }
    if (!globals.isStationEnabled) {
        return;
    }

    ExchangeData data = new ExchangeData();
    String stationId = stationService.getStationId();
    if (stationId == null) {
        data.setCommand(new Protocol.RequestStationId());
    }
    data.setStationId(stationId);

    if (stationId != null) {
        // always report about current active sequences, if we have actual stationId
        data.setCommand(stationTaskService.produceStationSequenceStatus());
        data.setCommand(stationService.produceReportStationStatus());
        final boolean b = stationTaskService.isNeedNewExperimentSequence(stationId);
        if (b) {
            data.setCommand(new Protocol.RequestTask(globals.isAcceptOnlySignedSnippets));
        }
        if (System.currentTimeMillis() - lastRequestForMissingResources > 15_000) {
            data.setCommand(new Protocol.CheckForMissingOutputResources());
            lastRequestForMissingResources = System.currentTimeMillis();
        }
    }

    reportSequenceProcessingResult(data);

    List<Command> cmds;
    synchronized (commands) {
        cmds = new ArrayList<>(commands);
        commands.clear();
    }
    data.setCommands(cmds);

    // !!! always use data.setCommand() for correct initializing stationId !!!

    // we have to pull new tasks from server constantly
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (globals.isSecureRestUrl) {
            String auth = globals.restUsername + '=' + globals.restToken + ':' + globals.stationRestPassword;
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
            String authHeader = "Basic " + new String(encodedAuth);
            headers.set("Authorization", authHeader);
        }

        HttpEntity<ExchangeData> request = new HttpEntity<>(data, headers);

        ResponseEntity<ExchangeData> response = restTemplate.exchange(globals.serverRestUrl, HttpMethod.POST,
                request, ExchangeData.class);
        ExchangeData result = response.getBody();

        addCommands(commandProcessor.processExchangeData(result).getCommands());
        log.debug("fixedDelay(), {}", result);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            log.error("Error 401 accessing url {}, globals.isSecureRestUrl: {}", globals.serverRestUrl,
                    globals.isSecureRestUrl);
        } else {
            throw e;
        }
    } catch (RestClientException e) {
        log.error("Error accessing url: {}", globals.serverRestUrl);
        log.error("Stacktrace", e);
    }
}