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.formulaone.controller.merchant.MerchantControllerTest.java

/**
 * Test successful merchant creation//w  w  w.  j  a  v  a2s  .  c  o m
 * 
 * @throws Exception
 */
@Test
public void test_1_SuccessfulMerchantCreation() throws Exception {

    request = createMerchant();
    HttpEntity<MerchantRequest> entity = new HttpEntity<MerchantRequest>(request, httpHeaders);
    try {
        ResponseEntity<MerchantResponse> response = restTemplate.exchange(base.toString(), HttpMethod.POST,
                entity, MerchantResponse.class);

        MerchantResponse merchantResponse = response.getBody();
        assertThat(merchantResponse, notNullValue());
        assertThat(merchantResponse.getCompanyName(), equalTo(request.getCompany().getName()));
        assertThat(merchantResponse.getDescription(), equalTo(request.getBusinessDescription()));
        assertThat(merchantResponse.getFirstName(), equalTo(request.getOwnershipDetails().getFirstName()));
        assertThat(merchantResponse.getLastName(), equalTo(request.getOwnershipDetails().getLastName()));
        assertThat(merchantResponse.getMid(), notNullValue());

        assertThat(response.getStatusCode(), equalTo(HttpStatus.CREATED));

        createdId = merchantResponse.getId();

    } catch (Exception e) {
        fail("Unexpected exception happened: " + e.getMessage());

    }
}

From source file:cz.cvut.via.androidrestskeleton.SkeletonActivity.java

/** Called with the activity is first created. */
@Override//from www .j av a  2  s  .  c  om
public void onCreate(Bundle savedInstanceState) {

    // DISABLE policy not allowing network connections from main application thread
    // these calls normally HAVE to be done from worker threads/asynchronous threads/services ..
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    super.onCreate(savedInstanceState);

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.skeleton_activity);

    requestView = (CheckedTextView) findViewById(R.id.checkedTextRequest);
    responseView = (CheckedTextView) findViewById(R.id.checkedTextResponse);

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.create)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            PostalAddress address = new PostalAddress();
            address.setCity("new city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncPOST<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<String> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());
                    responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                            + result.getResponseEntity().getHeaders().toString());
                    lastCreatedLocation = result.getResponseEntity().getHeaders().getLocation().getPath();
                };
            }.execute(url);
        }
    });

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.list)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            RestTemplate restTemplate = new RestTemplate();

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/";

            new AsyncGET<PostalAddress[]>(requestEntity, PostalAddress[].class) {
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }
                        //+ requestEntity.getBody().toJSONString());
                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.update)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            PostalAddress address = new PostalAddress();
            address.setCity("updated city");
            address.setCountry("new country");
            address.setStreet("new street");
            address.setZipCode("zipcode");

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            new AsyncPUT<PostalAddress>(requestEntity) {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n"
                            + request.getBody().toJSONString());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.delete)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation;

            // get reponse
            new AsyncDELETE() {
                protected void onPostExecute(Response<Object> result) {
                    requestView.setText(url);

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {
                        responseView.setText("PUT method in Spring does not support return values..");
                    }
                };
            }.execute(url);
        }
    });

    ((Button) findViewById(R.id.query)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            HashMap<String, String> query = new HashMap<String, String>();
            query.put("setFilter", "street == streetParam");
            query.put("declareParameters", "String streetParam");
            query.put("setOrdering", "street desc");

            HashMap<String, String> parameters = new HashMap<String, String>();
            parameters.put("streetParam", "new street");

            RESTQuery q = new RESTQuery();
            q.setQuery(query);
            q.setParameters(parameters);

            // request
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(new MediaType("application", "json"));
            HttpEntity<RESTQuery> requestEntity = new HttpEntity<RESTQuery>(q, requestHeaders);

            // endpoint
            final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/q";

            // get reponse
            new AsyncPOST_QUERY<RESTQuery, PostalAddress[]>(requestEntity, PostalAddress[].class) {
                @Override
                protected void onPostExecute(Response<PostalAddress[]> result) {
                    requestView.setText(url + "\n\n" + request.getHeaders());

                    if (result.getEx() != null) {
                        showError(result.getEx());
                    } else {

                        StringBuilder text = new StringBuilder();
                        for (PostalAddress address : result.getResponseEntity().getBody()) {
                            text.append(address.toJSONString() + "\n\n");
                        }

                        responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n"
                                + result.getResponseEntity().getHeaders().toString() + "\n\n" + text);
                    }
                }
            }.execute(url);
        }
    });

}

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

@Test
public void testDefaultScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();/*from   ww  w .j  a va 2s .  c  o  m*/
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}

From source file:org.cloudfoundry.identity.uaa.login.integration.AutologinContollerIntegrationTests.java

@Test
public void testUnauthorizedWithoutPassword() {
    AutologinRequest request = new AutologinRequest();
    request.setUsername(testAccounts.getUserName());
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/autologin"),
            HttpMethod.POST, new HttpEntity<AutologinRequest>(request, headers), Map.class);
    assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, Object> result = (Map<String, Object>) entity.getBody();
    assertNull(result.get("code"));
}

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

public Todo edit(String accessToken, Todo todo) {
    // Set the headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + accessToken);
    headers.add("Content-Type", "application/json");

    // Post request
    HttpEntity<Todo> request = new HttpEntity<Todo>(todo, headers);
    Todo todoEdited = restTemplate.postForObject(OAUTH_RESOURCE_SERVER_URL + "/rest/todos/edit", request,
            Todo.class);

    return todoEdited;
}

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

/**
 * Method, where Disease information is pushed to server in order to create user.
 * All heavy lifting is made here.//from  w w  w  . j  ava2s. com
 *
 * @param diseases only one Disease object is accepted
 * @return information about created disease
 */
@Override
protected Disease doInBackground(Disease... diseases) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DISEASES;

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

    Disease disease = diseases[0];

    try {
        Log.d(TAG, url);

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

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

/**
 * Method, where artifact information is pushed to server in order to create user.
 * All heavy lifting is made here.//  www.  j  av  a2 s .c o m
 *
 * @param artifacts only one Artifact object is accepted
 * @return information about created artifact
 */
@Override
protected Artifact doInBackground(Artifact... artifacts) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_ARTIFACTS;

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

    Artifact artifact = artifacts[0];

    try {
        Log.d(TAG, url);

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

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

/**
 * Method, where person information is pushed to server in order to create user.
 * All heavy lifting is made here.// ww w.  j a  v  a2s .  c o m
 *
 * @param persons only one Person object is accepted
 * @return information about created user
 */
@Override
protected Person doInBackground(Person... persons) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_USER + "create";

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

    Person person = persons[0];

    try {
        Log.d(TAG, url);

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

From source file:de.pksoftware.springstrap.sapi.controller.UpdateController.java

@RequestMapping(value = "/update-client", produces = "application/zip")
public HttpEntity<ByteArrayResource> updateClient() throws IOException, URISyntaxException {
    //String archiveFileName = clientSystemConfig.system.id + "-" + clientSystemConfig.system.version + ".zip";

    String archiveFileName = "springstrap-server.zip";

    //File file = new File("/home/pksoftware/dev-temp/ui5os-server-temp/" + archiveFileName);

    /*//  w  ww.ja  v  a 2s  .co m
    if(file.exists()){
       logger.info("Update already packaged: {}", file.getAbsolutePath());
               
       FileInputStream fin = new FileInputStream(file);
       byteArray = new byte[(int)file.length()];
               
       // Reads up to certain bytes of data from this input stream into an array of bytes.
       fin.read(byteArray);
               
       fin.close();
    }
    else{
    */
    logger.info("Building update package...");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    WebappZipper zipper = new WebappZipper(outputStream, servletContext);

    zipper.addResource("classpath*:/webjar/**", false);

    //zipper.addResource("/system/**", servletContext);
    zipper.addResource("/apps/**", true);
    zipper.addResource("/lib/**", true);

    zipper.addResource("/admin.html", true);
    zipper.addResource("/account.html", true);
    zipper.addResource("/microapp.html", true);

    zipper.close();

    byteArray = outputStream.toByteArray();

    outputStream.close();

    /*
    FileOutputStream fop = new FileOutputStream(file);
    fop.write(byteArray);
    fop.flush();
    fop.close();
    */
    //}

    //Send response

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(byteArray.length);
    headers.set("Content-Disposition", "attachment; filename=\"" + archiveFileName + "\"");

    return new HttpEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers);

}

From source file:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java

@Test
public void testDenied() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "user");
    form.set("password", "user");
    getCsrf(form, headers);//from   w ww. j  a v  a2s .c  o  m
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login",
            HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    String cookie = entity.getHeaders().getFirst("Set-Cookie");
    headers.set("Cookie", cookie);
    ResponseEntity<String> page = new TestRestTemplate().exchange(entity.getHeaders().getLocation(),
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.FORBIDDEN, page.getStatusCode());
    assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(),
            page.getBody().contains("Access denied"));
}