类org.springframework.http.HttpHeaders源码实例Demo

下面列出了怎么用org.springframework.http.HttpHeaders的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			int contentLength = (int) headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
源代码2 项目: spring-data-dev-tools   文件: Jira.java
private JiraReleaseVersions getJiraReleaseVersions(ProjectKey projectKey, HttpHeaders headers, int startAt) {

		Map<String, Object> parameters = newUrlTemplateVariables();
		parameters.put("project", projectKey.getKey());
		parameters.put("fields", "summary,status,resolution,fixVersions");
		parameters.put("startAt", startAt);

		try {
			return operations.exchange(PROJECT_VERSIONS_TEMPLATE, HttpMethod.GET, new HttpEntity<>(headers),
					JiraReleaseVersions.class, parameters).getBody();
		} catch (HttpStatusCodeException e) {

			System.out.println(e.getResponseBodyAsString());
			throw e;
		}
	}
 
源代码3 项目: spring-analysis-note   文件: RestTemplateTests.java
@Test
public void postForLocation() throws Exception {
	mockSentRequest(POST, "https://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);
	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("https://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	URI result = template.postForLocation("https://example.com", helloWorld);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
/**
 * Parse the body as form data and compare to the given {@code MultiValueMap}.
 * @since 4.3
 */
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
	return request -> {
		HttpInputMessage inputMessage = new HttpInputMessage() {
			@Override
			public InputStream getBody() throws IOException {
				MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
				return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		};
		FormHttpMessageConverter converter = new FormHttpMessageConverter();
		assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
	};
}
 
@Test
@WithMockUser
public void createPostWithMockUser() throws Exception {
    Post _data = Post.builder().title("my first post").content("my content of my post").build();
    given(this.postService.createPost(any(PostForm.class)))
        .willReturn(_data);
    
    MvcResult result = this.mockMvc
        .perform(
            post("/posts")
                .content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build()))
                .contentType(MediaType.APPLICATION_JSON)
        )
        .andExpect(status().isCreated())
        .andExpect(header().string(HttpHeaders.LOCATION, containsString("/posts")))
        .andReturn();
    
    log.debug("mvc result::" + result.getResponse().getContentAsString());
    
    verify(this.postService, times(1)).createPost(any(PostForm.class));
}
 
@Test
public void testExceedingCapacity() {
    ResponseEntity<String> response = this.restTemplate.getForEntity("/serviceB", String.class);
    HttpHeaders headers = response.getHeaders();
    String key = "rate-limit-application_serviceB_127.0.0.1";
    assertHeaders(headers, key, false, false);
    assertEquals(OK, response.getStatusCode());

    for (int i = 0; i < 2; i++) {
        response = this.restTemplate.getForEntity("/serviceB", String.class);
    }

    assertEquals(TOO_MANY_REQUESTS, response.getStatusCode());
    assertNotEquals(RedisApplication.ServiceController.RESPONSE_BODY, response.getBody());

    await().pollDelay(2, TimeUnit.SECONDS).untilAsserted(() -> {
        final ResponseEntity<String> responseAfterReset = this.restTemplate
            .getForEntity("/serviceB", String.class);
        final HttpHeaders headersAfterReset = responseAfterReset.getHeaders();
        assertHeaders(headersAfterReset, key, false, false);
        assertEquals(OK, responseAfterReset.getStatusCode());
    });
}
 
@Test
public void preflightRequestCredentials() throws Exception {
	this.request.setMethod(HttpMethod.OPTIONS.name());
	this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1");
	this.conf.addAllowedOrigin("http://domain1.com");
	this.conf.addAllowedOrigin("http://domain2.com");
	this.conf.addAllowedOrigin("http://domain3.com");
	this.conf.addAllowedHeader("Header1");
	this.conf.setAllowCredentials(true);

	this.processor.processRequest(this.conf, this.request, this.response);
	assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("http://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN,
			HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals(HttpServletResponse.SC_OK, this.response.getStatus());
}
 
源代码8 项目: spring-analysis-note   文件: CorsWebFilterTests.java
@Test
public void validActualRequest() {
	WebFilterChain filterChain = filterExchange -> {
		try {
			HttpHeaders headers = filterExchange.getResponse().getHeaders();
			assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
			assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
		}
		catch (AssertionError ex) {
			return Mono.error(ex);
		}
		return Mono.empty();

	};
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.get("https://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "https://domain2.com")
					.header("header2", "foo"));
	this.filter.filter(exchange, filterChain).block();
}
 
源代码9 项目: cubeai   文件: WebConfigurerTest.java
@Test
public void testCorsFilterOnOtherPath() throws Exception {
    props.getCors().setAllowedOrigins(Collections.singletonList("*"));
    props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    props.getCors().setAllowedHeaders(Collections.singletonList("*"));
    props.getCors().setMaxAge(1800L);
    props.getCors().setAllowCredentials(true);

    MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
        .addFilters(webConfigurer.corsFilter())
        .build();

    mockMvc.perform(
        get("/test/test-cors")
            .header(HttpHeaders.ORIGIN, "other.domain.com"))
        .andExpect(status().isOk())
        .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
源代码10 项目: tutorials   文件: PaginationUtilUnitTest.java
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
源代码11 项目: servicecomb-java-chassis   文件: ApolloClient.java
@SuppressWarnings("unchecked")
void refreshConfig() {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Content-Type", "application/json;charset=UTF-8");
  headers.add("Authorization", token);
  HttpEntity<String> entity = new HttpEntity<>(headers);
  ResponseEntity<String> exchange = rest.exchange(composeAPI(), HttpMethod.GET, entity, String.class);
  if (HttpResponseStatus.OK.code() == exchange.getStatusCode().value()) {
    try {
      Map<String, Object> body = JsonUtils.OBJ_MAPPER.readValue(exchange.getBody(),
          new TypeReference<Map<String, Object>>() {
          });
      refreshConfigItems((Map<String, Object>) body.get("configurations"));
    } catch (IOException e) {
      LOGGER.error("JsonObject parse config center response error: ", e);
    }
  } else {
    LOGGER.error("fetch configuration failed, error code:{} for {}",
        exchange.getStatusCodeValue(),
        exchange.getBody());
  }
}
 
源代码12 项目: JuniperBot   文件: DogApiService.java
@PostConstruct
public void init() {
    String apiKey = workerProperties.getDogApi().getKey();
    if (StringUtils.isEmpty(apiKey)) {
        return;
    }
    this.restTemplate = new RestTemplateBuilder()
            .rootUri(BASE_URI)
            .setConnectTimeout(HTTP_TIMEOUT_DURATION)
            .setReadTimeout(HTTP_TIMEOUT_DURATION)
            .uriTemplateHandler(new DefaultUriBuilderFactory(BASE_URI))
            .additionalInterceptors((request, body, execution) -> {
                HttpHeaders headers = request.getHeaders();
                headers.add("x-api-key", apiKey);
                headers.add("User-Agent", "JuniperBot");
                return execution.execute(request, body);
            })
            .build();
}
 
@Override
public String getServerName() {
	String host = getHeader(HttpHeaders.HOST);
	if (host != null) {
		host = host.trim();
		if (host.startsWith("[")) {
			host = host.substring(1, host.indexOf(']'));
		}
		else if (host.contains(":")) {
			host = host.substring(0, host.indexOf(':'));
		}
		return host;
	}

	// else
	return this.serverName;
}
 
源代码14 项目: servicecomb-java-chassis   文件: JaxrsClient.java
private static void testExchange(RestTemplate template, String cseUrlPrefix) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Accept", MediaType.APPLICATION_JSON);
  Person person = new Person();
  person.setName("world");
  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  ResponseEntity<Person> resEntity = template.exchange(cseUrlPrefix + "/compute/sayhello",
      HttpMethod.POST,
      requestEntity,
      Person.class);
  TestMgr.check("hello world", resEntity.getBody());

  ResponseEntity<String> resEntity2 =
      template.exchange(cseUrlPrefix + "/compute/addstring?s=abc&s=def", HttpMethod.DELETE, null, String.class);
  TestMgr.check("abcdef", resEntity2.getBody());
}
 
源代码15 项目: molgenis   文件: HttpClientConfigTest.java
@Test
void testGsonSerialization() {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  headers.set("Authorization", "Basic ABCDE");

  HttpEntity<TestNegotiatorQuery> entity = new HttpEntity<>(testNegotiatorQuery, headers);
  server
      .expect(once(), requestTo("http://directory.url/request"))
      .andExpect(method(HttpMethod.POST))
      .andExpect(content().string("{\"URL\":\"url\",\"nToken\":\"ntoken\"}"))
      .andExpect(MockRestRequestMatchers.header("Authorization", "Basic ABCDE"))
      .andRespond(withCreatedEntity(URI.create("http://directory.url/request/DEF")));

  String redirectURL =
      restTemplate.postForLocation("http://directory.url/request", entity).toASCIIString();
  assertEquals("http://directory.url/request/DEF", redirectURL);

  // Verify all expectations met
  server.verify();
}
 
源代码16 项目: openapi-generator   文件: ApiKeyAuthTest.java
@Test
public void testApplyToParamsInHeaderWithPrefix() {
    MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    HttpHeaders headerParams = new HttpHeaders();
    MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();

    ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
    auth.setApiKey("my-api-token");
    auth.setApiKeyPrefix("Token");
    auth.applyToParams(queryParams, headerParams, cookieParams);

    // no changes to query or cookie parameters
    assertEquals(0, queryParams.size());
    assertEquals(0, cookieParams.size());
    assertEquals(1, headerParams.size());
    assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN").get(0));
}
 
@Test
public void addHeadersOnlyOnceTest() throws IOException {
    TaggingRequestInterceptor testedInterceptor = new TaggingRequestInterceptor(TEST_VERSION_VALUE, TEST_ORG_VALUE, TEST_SPACE_VALUE);
    testedInterceptor.intercept(requestStub, body, execution);
    testedInterceptor.intercept(requestStub, body, execution);
    testedInterceptor.intercept(requestStub, body, execution);
    HttpHeaders headers = requestStub.getHeaders();
    String expectedValue = testedInterceptor.getHeaderValue(TEST_VERSION_VALUE);
    long tagCount = headers.get(TaggingRequestInterceptor.TAG_HEADER_NAME)
                           .stream()
                           .filter(value -> value.equals(expectedValue))
                           .count();
    assertEquals("Main tag header occurrence is not 1", 1L, tagCount);
    long orgTagCount = headers.get(TaggingRequestInterceptor.TAG_HEADER_ORG_NAME)
                              .stream()
                              .filter(value -> value.equals(TEST_ORG_VALUE))
                              .count();
    assertEquals("Org tag header occurrence is not 1", 1L, orgTagCount);
    long spaceTagCount = headers.get(TaggingRequestInterceptor.TAG_HEADER_SPACE_NAME)
                                .stream()
                                .filter(value -> value.equals(TEST_SPACE_VALUE))
                                .count();
    assertEquals("Space tag header occurrence is not 1", 1L, spaceTagCount);
}
 
源代码18 项目: davos   文件: PushbulletNotifyAction.java
@Override
public void execute(PostDownloadExecution execution) {

    PushbulletRequest body = new PushbulletRequest();
    body.body = execution.fileName;
    body.title = "A new file has been downloaded";
    body.type = "note";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + apiKey);

    try {

        LOGGER.info("Sending notification to Pushbullet for {}", execution.fileName);
        LOGGER.debug("API Key: {}", apiKey);
        HttpEntity<PushbulletRequest> httpEntity = new HttpEntity<PushbulletRequest>(body, headers);
        LOGGER.debug("Sending message to Pushbullet: {}", httpEntity);
        restTemplate.exchange("https://api.pushbullet.com/v2/pushes", HttpMethod.POST, httpEntity, Object.class);

    } catch (RestClientException | HttpMessageConversionException e ) {
        
        LOGGER.debug("Full stacktrace", e);
        LOGGER.error("Unable to complete notification to Pushbullet. Given error: {}", e.getMessage());
    }
}
 
源代码19 项目: spring-analysis-note   文件: CrossOriginTests.java
@Test
public void ambiguousProducesPreFlightRequest() throws Exception {
	this.handlerMapping.registerHandler(new MethodLevelController());
	this.request.setMethod("OPTIONS");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.setRequestURI("/ambiguous-produces");
	HandlerExecutionChain chain = this.handlerMapping.getHandler(request);
	CorsConfiguration config = getCorsConfiguration(chain, true);
	assertNotNull(config);
	assertArrayEquals(new String[] {"*"}, config.getAllowedMethods().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray());
	assertTrue(config.getAllowCredentials());
	assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders()));
	assertNull(config.getMaxAge());
}
 
源代码20 项目: frostmourne   文件: MessageService.java
boolean sendHttpPost(String httpPostEndPoint, AlarmMessage alarmMessage) {
    try {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        Map<String, Object> data = new HashMap<>();
        data.put("recipients", alarmMessage.getRecipients());
        data.put("content", alarmMessage.getContent());
        data.put("title", alarmMessage.getTitle());
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(httpPostEndPoint, request, String.class);
        return responseEntity.getStatusCode() == HttpStatus.OK;
    } catch (Exception ex) {
        LOGGER.error("error when send http post, url: " + httpPostEndPoint, ex);
        return false;
    }
}
 
@Test
public void postForLocationCallback() throws Exception  {
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(new MediaType("text", "plain", Charset.forName("ISO-8859-15")));
	HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
	final URI expected = new URI(baseUrl + "/post/1");
	ListenableFuture<URI> locationFuture = template.postForLocation(baseUrl + "/{method}", entity, "post");
	locationFuture.addCallback(new ListenableFutureCallback<URI>() {
		@Override
		public void onSuccess(URI result) {
			assertEquals("Invalid location", expected, result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	while (!locationFuture.isDone()) {
	}
}
 
@Test
public void getBodyViaRequestParameterWithRequestEncoding() throws Exception {
	MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
		@Override
		public HttpHeaders getMultipartHeaders(String paramOrFileName) {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return headers;
		}
	};

	byte[] bytes = {(byte) 0xC4};
	mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
	mockRequest.setCharacterEncoding("iso-8859-1");
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
/**
 * This implementation sets the default headers by calling {@link #addDefaultHeaders},
 * and then calls {@link #writeInternal}.
 */
public final void write(final T t, @Nullable final Type type, @Nullable MediaType contentType,
		HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

	final HttpHeaders headers = outputMessage.getHeaders();
	addDefaultHeaders(headers, t, contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> writeInternal(t, type, new HttpOutputMessage() {
			@Override
			public OutputStream getBody() {
				return outputStream;
			}
			@Override
			public HttpHeaders getHeaders() {
				return headers;
			}
		}));
	}
	else {
		writeInternal(t, type, outputMessage);
		outputMessage.getBody().flush();
	}
}
 
源代码24 项目: cubeai   文件: PaginationUtilUnitTest.java
@Test
public void greaterSemicolonTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content);
    String query = "Test>;test";
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 2);
    String[] linksData = headerData.split(",");
    assertTrue(linksData.length == 2);
    assertTrue(linksData[0].split(">;").length == 2);
    assertTrue(linksData[1].split(">;").length == 2);
    String expectedData = "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"last\","
            + "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(0L));
}
 
源代码25 项目: tds   文件: MetadataController.java
@RequestMapping(value = "**")
public ResponseEntity<String> getMetadata(@Valid MetadataRequestParameterBean params, BindingResult result,
    HttpServletResponse res, HttpServletRequest req) throws Exception {

  if (result.hasErrors())
    throw new BindException(result);
  String path = TdsPathUtils.extractPath(req, "metadata");

  try (GridDataset gridDataset = TdsRequestedDataset.getGridDataset(req, res, path)) {
    if (gridDataset == null)
      return null;

    NetcdfFile ncfile = gridDataset.getNetcdfFile(); // LOOK maybe gridDataset.getFileTypeId ??
    String fileTypeS = ncfile.getFileTypeId();
    ucar.nc2.constants.DataFormatType fileFormat = ucar.nc2.constants.DataFormatType.getType(fileTypeS);
    if (fileFormat != null)
      fileTypeS = fileFormat.toString(); // canonicalize

    ThreddsMetadata.VariableGroup vars = new ThreddsMetadataExtractor().extractVariables(fileTypeS, gridDataset);

    boolean wantXML = (params.getAccept() != null) && params.getAccept().equalsIgnoreCase("XML");

    HttpHeaders responseHeaders = new HttpHeaders();
    String strResponse;
    if (wantXML) {
      strResponse = writeXML(vars);
      responseHeaders.set(ContentType.HEADER, ContentType.xml.getContentHeader());
      // responseHeaders.set(Constants.Content_Disposition, Constants.setContentDispositionValue(datasetPath,
      // ".xml"));
    } else {
      strResponse = writeHTML(vars);
      responseHeaders.set(ContentType.HEADER, ContentType.html.getContentHeader());
    }
    return new ResponseEntity<>(strResponse, responseHeaders, HttpStatus.OK);
  }

}
 
源代码26 项目: lams   文件: MarshallingHttpMessageConverter.java
@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
	Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
	try {
		Object result = this.unmarshaller.unmarshal(source);
		if (!clazz.isInstance(result)) {
			throw new TypeMismatchException(result, clazz);
		}
		return result;
	}
	catch (UnmarshallingFailureException ex) {
		throw new HttpMessageNotReadableException("Could not read [" + clazz + "]", ex);
	}
}
 
源代码27 项目: tutorials   文件: UserApi.java
/**
 * Logs user into the system
 * 
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid username/password supplied
 * @param username The user name for login
 * @param password The password for login in clear text
 * @return String
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public String loginUser(String username, String password) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'username' is set
    if (username == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser");
    }
    
    // verify the required parameter 'password' is set
    if (password == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser");
    }
    
    String path = UriComponentsBuilder.fromPath("/user/login").build().toUriString();
    
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password));

    final String[] accepts = { 
        "application/xml", "application/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<String> returnType = new ParameterizedTypeReference<String>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
源代码28 项目: 21-points   文件: UserResource.java
/**
 * GET /users : get all users.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and with body all users
 */
@GetMapping("/users")
@Timed
public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
    final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
源代码29 项目: alcor   文件: IpAddrControllerTest.java
@Test
public void Test11_deactivateIpAddrStateBulkTest() throws Exception {
    IpAddrRequest ipAddrRequest1 = new IpAddrRequest(
            UnitTestConfig.ipVersion,
            UnitTestConfig.vpcId,
            UnitTestConfig.subnetId,
            UnitTestConfig.rangeId,
            UnitTestConfig.ip2,
            UnitTestConfig.deactivated);
    IpAddrRequest ipAddrRequest2 = new IpAddrRequest(
            UnitTestConfig.ipVersion,
            UnitTestConfig.vpcId,
            UnitTestConfig.subnetId,
            UnitTestConfig.rangeId,
            UnitTestConfig.ip3,
            UnitTestConfig.deactivated);

    List<IpAddrRequest> ipAddrRequests = new ArrayList<>();
    ipAddrRequests.add(ipAddrRequest1);
    ipAddrRequests.add(ipAddrRequest2);

    IpAddrRequestBulk ipAddrRequestBulk = new IpAddrRequestBulk();
    ipAddrRequestBulk.setIpRequests(ipAddrRequests);

    ObjectMapper objectMapper = new ObjectMapper();
    String ipAddrRequestBulkJson = objectMapper.writeValueAsString(ipAddrRequestBulk);

    this.mockMvc.perform(put(UnitTestConfig.ipAddrBulkUrl)
            .content(ipAddrRequestBulkJson)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());
}
 
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {
    return ExchangeFilterFunction.ofRequestProcessor(
        clientRequest -> {
            ClientRequest authorizedRequest = ClientRequest.from(clientRequest)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue())
                .build();
            return Mono.just(authorizedRequest);
        });
}
 
 类所在包
 同包方法