Java Code Examples for org.springframework.http.HttpHeaders#setAccept()

The following examples show how to use org.springframework.http.HttpHeaders#setAccept() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HealthApi.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
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())));
    }
    try {
        final ResponseEntity<String> responseEntity = restTemplate.exchange(
                url,
                GET,
                new HttpEntity<>("parameters", headers), String.class
        );
        content = responseEntity.getBody();
        statusCode = responseEntity.getStatusCode();
    } catch (HttpStatusCodeException e) {
        content = e.getStatusText();
        statusCode = e.getStatusCode();
    }
}
 
Example 2
Source File: TestParseServlet.java    From yauaa with Apache License 2.0 6 votes vote down vote up
@Before
public void ensureServiceHasStarted() throws InterruptedException {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(APPLICATION_JSON));
    headers.set("User-Agent", "Are we there yet?");

    HttpEntity<String> request = new HttpEntity<>("Are we there yet?", headers);

    HttpStatus statusCode = null;
    LOG.info("Is running?");

    while (statusCode != HttpStatus.OK) {
        if (statusCode != null) {
            LOG.info("No, not yet running (last code = {}).", statusCode);
            if (--attemptsRemaining == 0) {
                throw new IllegalStateException("Unable to initialize the parser.");
            }

        }
        Thread.sleep(100);
        ResponseEntity<String> response = this.restTemplate.exchange(getAliveURI(), GET, request, String.class);
        statusCode = response.getStatusCode();
    }
    LOG.info("Yes, it is running!");
}
 
Example 3
Source File: DefaultServerRequestTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void header() {
	HttpHeaders httpHeaders = new HttpHeaders();
	List<MediaType> accept =
			Collections.singletonList(MediaType.APPLICATION_JSON);
	httpHeaders.setAccept(accept);
	List<Charset> acceptCharset = Collections.singletonList(UTF_8);
	httpHeaders.setAcceptCharset(acceptCharset);
	long contentLength = 42L;
	httpHeaders.setContentLength(contentLength);
	MediaType contentType = MediaType.TEXT_PLAIN;
	httpHeaders.setContentType(contentType);
	InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
	httpHeaders.setHost(host);
	List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
	httpHeaders.setRange(range);

	MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/");
	httpHeaders.forEach(servletRequest::addHeader);
	servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);

	DefaultServerRequest request = new DefaultServerRequest(servletRequest,
			this.messageConverters);

	ServerRequest.Headers headers = request.headers();
	assertEquals(accept, headers.accept());
	assertEquals(acceptCharset, headers.acceptCharset());
	assertEquals(OptionalLong.of(contentLength), headers.contentLength());
	assertEquals(Optional.of(contentType), headers.contentType());
	assertEquals(httpHeaders, headers.asHttpHeaders());
}
 
Example 4
Source File: SpringHttpMessageConvertersLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
    final String URI = BASE_URI + "foos/{id}";

    final RestTemplate restTemplate = new RestTemplate();

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    final HttpEntity<String> entity = new HttpEntity<String>(headers);

    final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
    final Foo resource = response.getBody();

    assertThat(resource, notNullValue());
}
 
Example 5
Source File: ResponseEntityExceptionHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Customize the response for HttpMediaTypeNotSupportedException.
 * <p>This method sets the "Accept" header and delegates to
 * {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param request the current request
 * @return a {@code ResponseEntity} instance
 */
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
		HttpHeaders headers, HttpStatus status, WebRequest request) {

	List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		headers.setAccept(mediaTypes);
	}

	return handleExceptionInternal(ex, null, headers, status, request);
}
 
Example 6
Source File: ProductServiceImpl.java    From poi with Apache License 2.0 5 votes vote down vote up
@Override
public List excelImport(HttpServletRequest request) {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
	HttpEntity<String> entity = new HttpEntity<String>(headers);
	List<List<Object>> list = restTemplate.exchange(
			Globals.getBasePath(request) + "excel/read/productImport",
			HttpMethod.GET, entity, List.class).getBody();
	for (int i = 1; i < list.size(); i++) {
		List<Object> objList = list.get(i);
		Long id = Long.valueOf(objList.get(0).toString());
		boolean flag = productRepository.exists(id);
		if (!flag) {
			Product product = new Product();
			product.setId(id);
			if (null != objList.get(1)) {
				product.setDescription(objList.get(1).toString());
			}
			if (objList.size() > 2 && null != objList.get(2)) {
				product.setPrice(new BigDecimal(objList.get(2).toString()));
			}
			if (objList.size() > 3 && null != objList.get(3)) {
				product.setImageUrl(objList.get(3).toString());
			}
			saveOrUpdate(product);
		} else {
		}
	}
	return list;
}
 
Example 7
Source File: CatalogWebIntegrationTest.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
private <T> T getForMediaType(Class<T> value, MediaType mediaType,
		String url) {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(mediaType));

	HttpEntity<String> entity = new HttpEntity<String>("parameters",
			headers);

	ResponseEntity<T> resultEntity = restTemplate.exchange(url,
			HttpMethod.GET, entity, value);

	return resultEntity.getBody();
}
 
Example 8
Source File: AbstractRequestMappingIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
<T> ResponseEntity<T> performPost(String url, MediaType in, Object body, MediaType out, Class<T> type)
		throws Exception {

	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(in);
	if (out != null) {
		headers.setAccept(Collections.singletonList(out));
	}
	return  getRestTemplate().exchange(preparePost(url, headers, body), type);
}
 
Example 9
Source File: Scanner.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] getMediaFileData(String mediaFileId) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(MediaType.parseMediaTypes("audio/webm,audio/ogg,audio/wav,audio/*;"));
    ResponseEntity<byte[]> response = rest.exchange(
            addRestParameters(UriComponentsBuilder.fromHttpUrl(SERVER + "/rest/stream"))
                    .queryParam("id", mediaFileId)
                    .toUriString(),
            HttpMethod.GET,
            new HttpEntity<>(headers),
            byte[].class);

    assertThat(response.getBody()).hasSize((int) response.getHeaders().getContentLength());
    return response.getBody();
}
 
Example 10
Source File: ResponseEntityExceptionHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Customize the response for HttpMediaTypeNotSupportedException.
 * <p>This method sets the "Accept" header and delegates to
 * {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param request the current request
 * @return a {@code ResponseEntity} instance
 */
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
		HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

	List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		headers.setAccept(mediaTypes);
	}

	return handleExceptionInternal(ex, null, headers, status, request);
}
 
Example 11
Source File: GoogleSearchProviderImpl.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private GoogleGroupIndex readGoogleGroupIndex(final String group, final String url, int connectTimeout, int readTimeout) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
        setTimeout(restTemplate, connectTimeout, readTimeout);
        ObjectMapper mapper = Jackson2ObjectMapperBuilder.xml().build();
        mapper = mapper.addHandler(new DeserializationProblemHandler() {
            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
                if (beanOrClass instanceof GoogleGroupIndex) {
                    if ("versions".equals(propertyName)) {
                        if (((GoogleGroupIndex) beanOrClass).lastArtifactId != null) {
                            ((GoogleGroupIndex) beanOrClass).downloaded.put(((GoogleGroupIndex) beanOrClass).lastArtifactId, p.getText());
                            ((GoogleGroupIndex) beanOrClass).lastArtifactId = null;
                        }
                    } else {
                        ((GoogleGroupIndex) beanOrClass).lastArtifactId = propertyName;
                    }
                    return true;
                }
                return false;
            }

        });
        restTemplate.getMessageConverters().clear();
        restTemplate.getMessageConverters().add(new MappingJackson2XmlHttpMessageConverter(mapper));
        ResponseEntity<GoogleGroupIndex> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(requestHeaders), GoogleGroupIndex.class);
        GoogleGroupIndex groupIndex = response.getBody();
        groupIndex.group = group;
        groupIndex.url = url;
        return groupIndex.build();
    } catch (Exception exception) {
        Exceptions.printStackTrace(exception);
    }
    return null;
}
 
Example 12
Source File: TestParseServlet.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHtml() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(TEXT_HTML));
    headers.set("User-Agent", USERAGENT);

    HttpEntity<String> request = new HttpEntity<>("Niels Basjes", headers);

    ResponseEntity<String> response = this.restTemplate
        .exchange(getURI("/"), GET, request, String.class);

    assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.OK);

    assertThat(response.getBody()).contains("<td>Name Version</td><td>" + EXPECT_AGENT_NAME_VERSION + "</td>");
}
 
Example 13
Source File: FeatureTogglesControllerAcceptanceTest.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
ResponseEntity<String> getResource(final String url) {
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(singletonList(MediaType.APPLICATION_JSON));

    return restTemplate.exchange(
            url,
            GET,
            new HttpEntity<>("parameters", headers), String.class
    );
}
 
Example 14
Source File: ApplicationTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void adminLoads() {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().exchange(
			"http://localhost:" + this.port + BASE_PATH + "/env", HttpMethod.GET,
			new HttpEntity<>("parameters", headers), Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example 15
Source File: SpringHttpMessageConvertersLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() {
    final String URI = BASE_URI + "foos/{id}";

    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter()));
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF));
    final HttpEntity<String> entity = new HttpEntity<String>(headers);

    final ResponseEntity<FooProtos.Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1");
    final FooProtos.Foo resource = response.getBody();

    assertThat(resource, notNullValue());
}
 
Example 16
Source File: SkilClient.java    From SKIL_Examples with Apache License 2.0 5 votes vote down vote up
private <T> HttpEntity<T> createEntity(T entity) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + token);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    return new HttpEntity<>(entity, headers);
}
 
Example 17
Source File: AbstractRequestMappingIntegrationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
<T> ResponseEntity<T> performGet(String url, MediaType out, Class<T> type) throws Exception {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Collections.singletonList(out));
	return getRestTemplate().exchange(prepareGet(url, headers), type);
}
 
Example 18
Source File: ShippingWebIntegrationTest.java    From microservice-atom with Apache License 2.0 3 votes vote down vote up
private <T> T getForMediaType(Class<T> value, MediaType mediaType, String url) {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(mediaType));

	HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

	ResponseEntity<T> resultEntity = restTemplate.exchange(url, HttpMethod.GET, entity, value);

	return resultEntity.getBody();
}
 
Example 19
Source File: CatalogWebIntegrationTest.java    From microservice-kubernetes with Apache License 2.0 3 votes vote down vote up
private <T> T getForMediaType(Class<T> value, MediaType mediaType, String url) {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(mediaType));

	HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

	ResponseEntity<T> resultEntity = restTemplate.exchange(url, HttpMethod.GET, entity, value);

	return resultEntity.getBody();
}
 
Example 20
Source File: BonusWebIntegrationTest.java    From microservice-istio with Apache License 2.0 3 votes vote down vote up
private <T> T getForMediaType(Class<T> value, MediaType mediaType, String url) {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(mediaType));

	HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

	ResponseEntity<T> resultEntity = restTemplate.exchange(url, HttpMethod.GET, entity, value);

	return resultEntity.getBody();
}