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.tce.oauth2.spring.client.services.TodoService.java

public TodoResponse delete(String accessToken, Long id) {
    // Set the headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + accessToken);
    headers.add("Content-Type", "application/json");

    // Post request
    HttpEntity<String> request = new HttpEntity<String>("", headers);
    TodoResponse response = restTemplate.postForObject(
            OAUTH_RESOURCE_SERVER_URL + "/rest/todos/" + id + "/delete", request, TodoResponse.class);

    return response;
}

From source file:com.taxamo.example.ec.ApplicationController.java

/**
 * This method initializes Express Checkout token with PayPal and then redirects to Taxamo checkout form.
 *
 * Please note that only Express Checkout token is provided to Taxamo - and Taxamo will use
 * provided PayPal credentials to get order details from it and render the checkout form.
 *
 *
 * @param model//ww  w.  j  a  v  a2 s  .  co  m
 * @return
 */
@RequestMapping("/express-checkout")
public String expressCheckout(Model model) {

    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("USER", ppUser);
    map.add("PWD", ppPass);
    map.add("SIGNATURE", ppSign);
    map.add("VERSION", "117");
    map.add("METHOD", "SetExpressCheckout");
    map.add("returnUrl", properties.getProperty(PropertiesConstants.STORE)
            + properties.getProperty(PropertiesConstants.CONFIRM_LINK));
    map.add("cancelUrl", properties.getProperty(PropertiesConstants.STORE)
            + properties.getProperty(PropertiesConstants.CANCEL_LINK));

    //shopping item(s)
    map.add("PAYMENTREQUEST_0_AMT", "20.00"); // total amount
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");
    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");

    map.add("L_PAYMENTREQUEST_0_NAME0", "ProdName");
    map.add("L_PAYMENTREQUEST_0_DESC0", "ProdName desc");
    map.add("L_PAYMENTREQUEST_0_AMT0", "20.00");
    map.add("L_PAYMENTREQUEST_0_QTY0", "1");
    map.add("L_PAYMENTREQUEST_0_ITEMCATEGORY0", "Digital");

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    template.setMessageConverters(messageConverters);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
            requestHeaders);
    ResponseEntity<String> res = template.exchange(
            URI.create(properties.get(PropertiesConstants.PAYPAL_NVP).toString()), HttpMethod.POST, request,
            String.class);

    Map<String, List<String>> params = parseQueryParams(res.getBody());

    String ack = params.get("ACK").get(0);
    if (!ack.equals("Success")) {
        model.addAttribute("error", params.get("L_LONGMESSAGE0").get(0));
        return "error";
    } else {
        String token = params.get("TOKEN").get(0);
        return "redirect:" + properties.get(PropertiesConstants.TAXAMO) + "/checkout/index.html?" + "token="
                + token + "&public_token=" + publicToken + "&cancel_url="
                + new String(
                        Base64.encodeBase64((properties.getProperty(PropertiesConstants.STORE)
                                + properties.getProperty(PropertiesConstants.CANCEL_LINK)).getBytes()))
                + "&return_url="
                + new String(Base64.encodeBase64((properties.getProperty(PropertiesConstants.STORE)
                        + properties.getProperty(PropertiesConstants.CONFIRM_LINK)).getBytes()))
                + "#/paypal_express_checkout";
    }
}

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

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

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(VehicleFixtures.strandardVehicleJSON(), headers);

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

From source file:uta.ak.TestNodejsInterface.java

private void testFromDB() throws Exception {

    Connection con = null; //MYSQL
    Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
    System.out.println("connection yes");

    System.out.println("query records...");
    String querySQL = "SELECT" + "   * " + "FROM " + "   c_rawtext " + "WHERE " + "tag like 'function%'";

    PreparedStatement preparedStmt = con.prepareStatement(querySQL);
    ResultSet rs = preparedStmt.executeQuery();

    Set<String> filterDupSet = new HashSet<>();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);/*from w  w  w  .  ja  va  2s  .c om*/
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    while (rs.next()) {

        System.out.println(rs.getString("title") + "  " + rs.getString("text") + "  " + rs.getString("tag"));

        String formattedDate = format1.format(new Date());

        String interfaceMsg = "<message> " + "    <title> " + rs.getString("title") + "    </title> "
                + "    <text> " + StringEscapeUtils.escapeXml10(rs.getString("text")) + "    </text> "
                + "    <textCreatetime> " + formattedDate + "    </textCreatetime> " + "    <tag> "
                + rs.getString("tag") + "    </tag> " + "</message>";

        //            String restUrl="http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";
        String restUrl = "http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_XML);
        headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        //            headers.setContentLength();
        HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

        ResponseEntity<String> result = restTemplate.exchange(restUrl, HttpMethod.POST, entity, String.class);

        System.out.println(result.getBody());

    }

}

From source file:com.ge.predix.test.utils.PrivilegeHelper.java

public ResponseEntity<Object> postMultipleSubjects(final OAuth2RestTemplate acsTemplate, final String endpoint,
        final HttpHeaders headers, final BaseSubject... subjects) {
    Attribute site = getDefaultAttribute();
    Set<Attribute> attributes = new HashSet<>();
    attributes.add(site);/*from   w  w  w .j  av a2 s.co m*/

    List<BaseSubject> subjectsArray = new ArrayList<>();
    for (BaseSubject s : subjects) {
        s.setAttributes(attributes);
        subjectsArray.add(s);
    }
    URI subjectUri = URI.create(endpoint + ACS_SUBJECT_API_PATH);

    ResponseEntity<Object> responseEntity = acsTemplate.postForEntity(subjectUri,
            new HttpEntity<>(subjectsArray, headers), Object.class);

    return responseEntity;
}

From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    ResponseEntity<Map> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());/*ww w .j  av a 2  s. com*/
    headers = getAppBasicAuthHttpHeaders();
    headers.add("Cookie", cookies.get(0));

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true").build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token")
            .queryParam("response_type", "token").queryParam("grant_type", "authorization_code")
            .queryParam("code", newCode).queryParam("redirect_uri", appUrl).build().toUriString();

    ResponseEntity<Map> tokenResponse = template.exchange(tokenUrl, HttpMethod.POST,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    ResponseEntity<Void> loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());
    headers.clear();
    headers.add("Cookie", cookies.get(0));
    restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, headers), Void.class);

    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

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

/**
 * Method, where data file information is pushed to server in order to create data file record.
 * All heavy lifting is made here./*from w ww . j av  a  2s . co  m*/
 *
 * @param dataFileContents must be three params in order - experiment id, description, path to file
 * @return URI of uploaded file
 */
@Override
protected URI doInBackground(String... dataFileContents) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DATAFILE;

    setState(RUNNING, R.string.working_ws_upload_data_file);
    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());

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(dataFileContents[2]);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("experimentId", dataFileContents[0]);
        form.add("description", dataFileContents[1]);
        form.add("file", toBeUploadedFile);

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

From source file:com.wisemapping.test.rest.RestAccountITCase.java

private URI createUser(HttpHeaders requestHeaders, RestTemplate templateRest, RestUser restUser) {
    HttpEntity<RestUser> createUserEntity = new HttpEntity<RestUser>(restUser, requestHeaders);
    return templateRest.postForLocation(BASE_REST_URL + "/admin/users", createUserEntity);
}

From source file:fr.itldev.koya.services.impl.KoyaContentServiceImpl.java

private Document upload(User user, NodeRef parent, Object o) throws AlfrescoServiceException {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("filedata", o);
    parts.add("destination", parent.toString());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, headers);
    AlfrescoUploadReturn upReturn = fromJSON(new TypeReference<AlfrescoUploadReturn>() {
    }, user.getRestTemplate().postForObject(getAlfrescoServerUrl() + REST_POST_UPLOAD, request, String.class));

    return (Document) getSecuredItem(user, upReturn.getNodeRef());

}