Java org.springframework.http.ResponseEntity 代码实例

・23 分钟阅读

以下是展示如何使用org.springframework.http.ResponseEntity的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test
public void createAndDeleteUserServiceComposition() {
    // create a service composition
    ServiceCompositionCreateMessage serviceCompositionCreateMessage = new ServiceCompositionCreateMessage();
    serviceCompositionCreateMessage.setAuthorization("BEARER "
            + accessToken);
    serviceCompositionCreateMessage.setId(SERVICECOMPID);
    HttpEntity<ServiceCompositionCreateMessage> creationEntity = new HttpEntity<ServiceCompositionCreateMessage>(
            serviceCompositionCreateMessage);
    ResponseEntity<Object> responseEntityCreation = digestRestTemplate
            .exchange(URL + "idm/servicecomposition/", HttpMethod.POST,
                    creationEntity, Object.class);
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> scCreateResponse = (LinkedHashMap<String, Object>) responseEntityCreation
            .getBody();
    assertEquals(HttpStatus.CREATED, responseEntityCreation.getStatusCode());
    assertEquals(SERVICECOMPID, (String) scCreateResponse.get("id"));
    assertEquals(userId, (String) scCreateResponse.get("owner_id"));
    long lastModified = (long) scCreateResponse.get("lastModified");
    // delete service composition
    AuthenticatedEmptyMessage authenticateEmptyMes = new AuthenticatedEmptyMessage();
    authenticateEmptyMes.setAuthorization("Bearer " + accessToken);
    HttpHeaders header = new HttpHeaders();
    header.set("If-Unmodified-Since", String.valueOf(lastModified));
    HttpEntity<AuthenticatedEmptyMessage> deletionEntity = new HttpEntity<AuthenticatedEmptyMessage>(
            authenticateEmptyMes, header);
    ResponseEntity<Object> responseEntityDeletion = digestRestTemplate
            .exchange(URL + "idm/servicecomposition/" + SERVICECOMPID,
                    HttpMethod.DELETE, deletionEntity, Object.class);
    assertEquals(HttpStatus.OK, responseEntityDeletion.getStatusCode());
}
 

实例 2


@RequestMapping(value = BASE_MAPPING, method = GET,
                produces = { SPRING_DATA_COMPACT_JSON_VALUE, TEXT_URI_LIST_VALUE })
public ResponseEntity<ResourceSupport> followPropertyReferenceCompact(RootResourceInformation repoRequest,
                @BackendId Serializable id, @PathVariable String property, PersistentEntityResourceAssembler assembler)
                throws Exception {
        ResponseEntity<ResourceSupport> response = followPropertyReference(repoRequest, id, property, assembler);
        if (response.getStatusCode() != HttpStatus.OK) {
                return response;
        }
        ResourceMetadata repoMapping = repoRequest.getResourceMetadata();
        PersistentProperty<?> persistentProp = repoRequest.getPersistentEntity().getPersistentProperty(property);
        ResourceMapping propertyMapping = repoMapping.getMappingFor(persistentProp);
        ResourceSupport resource = response.getBody();
        List<Link> links = new ArrayList<Link>();
        ControllerLinkBuilder linkBuilder = linkTo(methodOn(RepositoryPropertyReferenceController.class)
                        .followPropertyReference(repoRequest, id, property, assembler));
        if (resource instanceof Resource) {
                Object content = ((Resource<?>) resource).getContent();
                if (content instanceof Iterable) {
                        for (Resource<?> res : (Iterable<Resource<?>>) content) {
                                links.add(linkBuilder.withRel(propertyMapping.getRel()));
                        }
                } else if (content instanceof Map) {
                        Map<Object, Resource<?>> map = (Map<Object, Resource<?>>) content;
                        for (Entry<Object, Resource<?>> entry : map.entrySet()) {
                                Link l = new Link(entry.getValue().getLink("self").getHref(), entry.getKey().toString());
                                links.add(l);
                        }
                }
        } else {
                links.add(linkBuilder.withRel(propertyMapping.getRel()));
        }
        return ControllerUtils.toResponseEntity(HttpStatus.OK, null, new Resource<Object>(EMPTY_RESOURCE_LIST, links));
}
 

实例 3


/**
 * Logs in the user
 * 
 * @param uid
 *            id of the user
 * @param pwd
 *            password of the user
 * @return molgenis session token
 */
public LoginResponse login(String uid, String pwd)
{
        ResponseEntity<LoginResponse> result = template.postForEntity("{apiHref}/login", LoginRequest.create(uid, pwd),
                        LoginResponse.class, apiHref);
        if (result.getStatusCode() == OK)
        {
                return result.getBody();
        }
        throw new RestClientException("Not authenticated");
}
 

实例 4


@Test
public void testCorsHeadersInResponse_forRootPage() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
        HttpHeaders headers = response.getHeaders();
        assertThat(headers.get("Access-Control-Allow-Origin"), equalTo(asList("*")));
        assertThat(headers.get("Access-Control-Allow-Methods"), equalTo(asList("POST, GET, OPTIONS, DELETE")));
        assertThat(headers.get("Access-Control-Max-Age"), equalTo(asList("3600")));
        assertThat(headers.get("Access-Control-Allow-Headers"), equalTo(asList("x-requested-with")));
}
 

实例 5


@Before
public void setup() {
    digestRestTemplate = digestRestTemplate();
    restTemplate = new RestTemplate();
    // Create user
    UserCreateMessage createMessage = new UserCreateMessage();
    createMessage.setUsername(USERNAME);
    createMessage.setPassword(PASSWORD);
    HttpEntity<UserCreateMessage> createUser = new HttpEntity<UserCreateMessage>(
            createMessage);
    ResponseEntity<Object> responseEntityCreation = digestRestTemplate
            .exchange(URL + "idm/user/", HttpMethod.POST, createUser,
                    Object.class);
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> userCreationResponse = (LinkedHashMap<String, Object>) responseEntityCreation
            .getBody();
    userId = (String) userCreationResponse.get("id");
    userLastModified = (long) userCreationResponse.get("lastModified");
    // Authenticate user
    UserCredentials ucredentials = new UserCredentials();
    ucredentials.setUsername(USERNAME);
    ucredentials.setPassword(PASSWORD);
    HttpEntity<UserCredentials> authUser = new HttpEntity<UserCredentials>(
            ucredentials);
    ResponseEntity<Object> responseEntityAuthentication = restTemplate
            .exchange(URL + "auth/user/", HttpMethod.POST, authUser,
                    Object.class);
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> authResponse = (LinkedHashMap<String, Object>) responseEntityAuthentication
            .getBody();
    accessToken = (String) authResponse.get("accessToken");
}
 

实例 6


@Test
public void createAndDeleteAttributeDefinitionsTest() {
    AttributeDefinitionCreateMessage attDef = new AttributeDefinitionCreateMessage();
    attDef.setName(ATTDEFNAME);
    attDef.setType(ATTDEFTYPE);
    // Set attribute details
    HttpHeaders header = new HttpHeaders();
    header.set("Authorization", "BEARER " + accessToken);
    HttpEntity<AttributeDefinitionCreateMessage> setAttDef = new HttpEntity<AttributeDefinitionCreateMessage>(
            attDef, header);
    ResponseEntity<Object> responseEntityDetails = restTemplate.exchange(
            URL + "idm/group/" + groupId + "/attribute_definition/",
            HttpMethod.POST, setAttDef, Object.class);
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> groupResponse = (LinkedHashMap<String, Object>) responseEntityDetails
            .getBody();
    assertEquals(HttpStatus.CREATED, responseEntityDetails.getStatusCode());
    assertEquals(ATTDEFNAME, (String) groupResponse.get("name"));
    assertEquals(ATTDEFTYPE, (String) groupResponse.get("type"));
    assertEquals(userId, (String) groupResponse.get("owner_id"));
    assertEquals(groupId, (String) groupResponse.get("group_id"));
    // delete attribute details
    System.out.println(groupResponse.get("lastModified"));
    long attLastModified = (long) groupResponse.get("lastModified");
    header = new HttpHeaders();
    header.set("Authorization", "BEARER " + accessToken);
    header.set("If-Unmodified-Since", String.valueOf(attLastModified));
    HttpEntity<String> deleteEntity = new HttpEntity<String>(header);
    ResponseEntity<Object> responseDeleteEntityDetails = restTemplate
            .exchange(URL + "idm/group/attribute_definition/"
                    + groupResponse.get("id") + "/", HttpMethod.DELETE,
                    deleteEntity, Object.class);
    assertEquals(HttpStatus.OK, responseDeleteEntityDetails.getStatusCode());
}
 

实例 7


@Before
public void setup() {
    digestRestTemplate = digestRestTemplate();
    restTemplate = new RestTemplate();
    // Create user
    UserCreateMessage createMessage = new UserCreateMessage();
    createMessage.setUsername(USERNAME);
    createMessage.setPassword(PASSWORD);
    HttpEntity<UserCreateMessage> createUser = new HttpEntity<UserCreateMessage>(
            createMessage);
    ResponseEntity<Object> responseEntityCreation = digestRestTemplate
            .exchange(URL + "idm/user/", HttpMethod.POST, createUser,
                    Object.class);
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> userCreationResponse = (LinkedHashMap<String, Object>) responseEntityCreation
            .getBody();
    userId = (String) userCreationResponse.get("id");
    userLastModified = (long) userCreationResponse.get("lastModified");
    // Authenticate user
    UserCredentials ucredentials = new UserCredentials();
    ucredentials.setUsername(USERNAME);
    ucredentials.setPassword(PASSWORD);
    HttpEntity<UserCredentials> authUser = new HttpEntity<UserCredentials>(
            ucredentials);
    ResponseEntity<Object> responseEntityAuthentication = restTemplate
            .exchange(URL + "auth/user/", HttpMethod.POST, authUser,
                    Object.class);
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, Object> authResponse = (LinkedHashMap<String, Object>) responseEntityAuthentication
            .getBody();
    accessToken = (String) authResponse.get("accessToken");
}
 

实例 8


private <T> T nextFact(final SubscriptionId subscriptionId, final Class<? extends T> classOfFact) {
    final ResponseEntity<? extends T> response = restTemplate.getForEntity(Paths.nextFact(subscriptionId), classOfFact);
    if (response.getStatusCode() == HttpStatus.NO_CONTENT) {
        return nextFact(subscriptionId, classOfFact);
    }
    return response.getBody();
}
 

实例 9


private static void getResource(final String url, final Optional<String> mediaType) {
    final HttpHeaders headers = new HttpHeaders();
    if (mediaType.isPresent()) {
        headers.setAccept(asList(parseMediaType(mediaType.get())));
    }
    final ResponseEntity<String> responseEntity = restTemplate.exchange(
            url,
            GET,
            new HttpEntity<>("parameters", headers), String.class
    );
    content = responseEntity.getBody();
    statusCode = responseEntity.getStatusCode();
}
 

实例 10


private BackendStatus downloadBackendStatus() throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
        Log.v( TAG, "downloadBackendStatus : enter" );
        ResponseEntity<org.mythtv.services.api.v025.status.beans.BackendStatus> status = mMythServicesTemplate.statusOperations().getStatus( ETagInfo.createEmptyETag() );
        if( status.getStatusCode() == HttpStatus.OK ) {
                if( null != status.getBody() ) {
                        ApiVersion apiVersion = MythAccessFactory.getMythVersion( mLocationProfile.getUrl() );
                        mLocationProfile.setVersion( apiVersion.name() );
                        mLocationProfile.setConnected( true );
                        mLocationProfile.setProtocolVersion( String.valueOf( status.getBody().getProtocolVersion() ) );
                        if( null != status.getBody().getMachineInfo() ) {
                                if( null != status.getBody().getMachineInfo().getGuide() ) {
                                        mLocationProfile.setNextMythFillDatabase( status.getBody().getMachineInfo().getGuide().getNext() );
                                }
                        }
                        mLocationProfileDaoHelper.save( mContext, mLocationProfile );
                        updateProgramGuide( mContext, status.getBody() );
                        return convertBackendStatus( status.getBody() );
                } else {
                        mLocationProfile.setConnected( false );
                        mLocationProfileDaoHelper.save( mContext, mLocationProfile );
                }
        }
        Log.v( TAG, "downloadBackendStatus : exit" );
        return null;
}
 

实例 11


private ResponseEntity<String> getMapItDataByCode(String postCode, boolean isPartialPostCode) {
        ResponseEntity<String> mapItResponse = null;
        if (isPartialPostCode) {
                mapItResponse = mapitService.getMapItDataForPartialPostCode(postCode);
        }
        else {
                mapItResponse = mapitService.getMapItDataForFullPostCode(postCode);
        }
        if (mapItResponse.getStatusCode() != HttpStatus.OK) {
                LOGGER.error("MapIt postcode lookup returned HttpResponse error code: "
                                + mapItResponse.getStatusCode());
                throw new RuntimeException("MapIt Service error,http code: "+ mapItResponse.getStatusCode());
        }
        return mapItResponse;
}
 

实例 12


public final boolean isSafe(String url) {
  final Map<String, String> formParameters = this.config.getParameters();
  formParameters.put(PARAMETER_URL, url);
  boolean safe = true;
  try {
    final ResponseEntity<String> response = client.getForEntity(
        config.getApiUrl(),
        String.class,
        formParameters);
    LOGGER.debug("Google Safe Browsing API returned HTTP Status: {} and message: {}", response.getStatusCode(), response.getBody());
    if (response.getStatusCode() == HttpStatus.OK) {
      LOGGER.debug("Possible unsafe link: {} - {}", url, response.getBody());
      safe = false;
    }
  } catch (RestClientException restException) {
    LOGGER.warn("Exception occurred during HTTP call to Google Safe Browsing API: {}", restException);
  }
  return safe;
}
 

实例 13


@SuppressWarnings("unchecked")
@Test
public void testClean() throws Exception {
        RabbitAdmin admin = new RabbitAdmin(test.getResource());
        final String uuid = UUID.randomUUID().toString();
        String queueName = MessageBusSupport.applyPrefix("xdbus.",
                        BusUtils.constructPipeName(uuid, 0));
        admin.declareQueue(new Queue(queueName));
        final FanoutExchange fanout = new FanoutExchange(
                        MessageBusSupport.applyPrefix("xdbus.", MessageBusSupport.applyPubSub(
                                        BusUtils.constructTapPrefix(uuid) + ".foo.bar")));
        admin.declareExchange(fanout);
        RestTemplate template = new RestTemplate();
        URI uri = new URI("http://localhost:" + adminPort + "/streams/clean/rabbit/" + queueName.substring(6));
        RequestEntity<String> request = new RequestEntity<>(HttpMethod.DELETE, uri);
        HttpStatus status = HttpStatus.NO_CONTENT;
        ResponseEntity<?> reply = null;
        int n = 0;
        while (n++ < 100 && !status.equals(HttpStatus.OK)) {
                reply = template.exchange(request, Map.class);
                status = reply.getStatusCode();
                Thread.sleep(100);
        }
        assertEquals("Didn't get OK after 10 seconds", HttpStatus.OK, reply.getStatusCode());
        Map<String, List<String>> body = (Map<String, List<String>>) reply.getBody();
        assertEquals(2, body.size());
        List<String> queues = body.get("queues");
        assertEquals(queueName, queues.get(0));
        List<String> exchanges = body.get("exchanges");
        assertEquals(fanout.getName(), exchanges.get(0));
        reply = template.exchange(request, Map.class);
        assertEquals(HttpStatus.NO_CONTENT, reply.getStatusCode());
}
 

实例 14


@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testLoginServerCfInvalidClientPasswordToken() throws Exception {
    ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept",MediaType.APPLICATION_JSON_VALUE);
    params.set("client_id", resource.getClientId());
    params.set("client_secret","bogus");
    params.set("source","login");
    params.set(UaaAuthenticationDetails.ADD_NEW, "false");
    params.set("grant_type", "password");
    String redirect = resource.getPreEstablishedRedirectUri();
    if (redirect != null) {
        params.set("redirect_uri", redirect);
    }
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAccessTokenUri(), params, headers);
    HttpStatus statusCode = response.getStatusCode();
    assertTrue("Status code should be 401 or 403.", statusCode==HttpStatus.FORBIDDEN || statusCode==HttpStatus.UNAUTHORIZED);
}
 

实例 15


/**
 * PUT  /authors -> Updates an existing author.
 */
@RequestMapping(value = "/authors",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> update(@Valid @RequestBody Author author) throws URISyntaxException {
    log.debug("REST request to update Author : {}", author);
    if (author.getId() == null) {
        return create(author);
    }
    authorRepository.save(author);
    return ResponseEntity.ok().build();
}
 
讨论
淘淘あ西西 profile image