@ApiOperation("postForEntity form") @RequestMapping(value = "/post3", method = RequestMethod.POST) @ResponseBody public Object postForEntity3(@RequestParam String name) { String url = HOST_MALL_ADMIN + "/productAttribute/category/create"; //设置头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //构造表单参数 MultiValueMap<String, String> params= new LinkedMultiValueMap<>(); params.add("name", name); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<CommonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, CommonResult.class); return responseEntity.getBody(); } }
@RequestMapping(path = "/something", method = OPTIONS) public HttpHeaders fooOptions() { HttpHeaders headers = new HttpHeaders(); headers.add("Allow", "PUT,POST"); return headers; }
@GetMapping("cookie-echo") ResponseEntity<Void> handleCookie(@CookieValue("k1") String cookieValue) { HttpHeaders headers = new HttpHeaders(); headers.set("Set-Cookie", "k1=" + cookieValue); return new ResponseEntity<>(headers, HttpStatus.OK); } }
/** * Retrieve a combined result from the field values of multi-valued headers. * @param headerName the header name * @return the combined result * @since 4.3 */ @Nullable protected String getFieldValues(String headerName) { List<String> headerValues = get(headerName); return (headerValues != null ? toCommaDelimitedString(headerValues) : null); }
@Override public HttpHeaders getMultipartHeaders(String paramOrFileName) { String contentType = getMultipartContentType(paramOrFileName); if (contentType != null) { HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", contentType); return headers; } else { return null; } }
@RequestMapping(value = "/{id}/uploadAsset", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Map<String, Object>> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, @PathVariable(value="sectionKey") String sectionKey, @PathVariable(value="id") String id) throws IOException { Map<String, Object> responseMap = new HashMap<String, Object>(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "text/html; charset=utf-8"); return new ResponseEntity<Map<String, Object>>(responseMap, responseHeaders, HttpStatus.OK);
@RequestMapping(value = BASE_MAPPING, method = GET) public ResponseEntity<ResourceSupport> followPropertyReference(final RootResourceInformation repoRequest, @BackendId Serializable id, final @PathVariable String property, final PersistentEntityResourceAssembler assembler) throws Exception { HttpHeaders headers = new HttpHeaders(); Function<ReferencedProperty, ResourceSupport> handler = prop -> prop.mapValue(it -> { if (prop.property.isCollectionLike()) { return toResources((Iterable<?>) it, assembler, prop.propertyType, Optional.empty()); } else if (prop.property.isMap()) { Map<Object, Resource<?>> resources = new HashMap<Object, Resource<?>>(); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) it).entrySet()) { resources.put(entry.getKey(), assembler.toResource(entry.getValue())); } return new Resource<Object>(resources); } else { PersistentEntityResource resource = assembler.toResource(it); headers.set("Content-Location", resource.getId().getHref()); return resource; } }).orElseThrow(() -> new ResourceNotFoundException()); return ControllerUtils.toResponseEntity(HttpStatus.OK, headers, // doWithReferencedProperty(repoRequest, id, property, handler, HttpMethod.GET)); }
/** * Get the logo image for a client * @param id */ @RequestMapping(value = "/{id}/logo", method=RequestMethod.GET, produces = { MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE }) public ResponseEntity<byte[]> getClientLogo(@PathVariable("id") Long id, Model model) { ClientDetailsEntity client = clientService.getClientById(id); if (client == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else if (Strings.isNullOrEmpty(client.getLogoUri())) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { // get the image from cache CachedImage image = clientLogoLoadingService.getLogo(client); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(image.getContentType())); headers.setContentLength(image.getLength()); return new ResponseEntity<>(image.getData(), headers, HttpStatus.OK); } }
@RequestMapping(method = POST) HttpEntity<Void> writeUserProfilePhoto(@PathVariable Long user, @RequestParam MultipartFile file) throws Throwable { byte bytesForProfilePhoto[] = FileCopyUtils.copyToByteArray(file.getInputStream()); this.crmService.writeUserProfilePhoto(user, MediaType.parseMediaType(file.getContentType()), bytesForProfilePhoto); Resource<User> userResource = this.userResourceAssembler.toResource(crmService.findById(user)); List<Link> linkCollection = userResource.getLinks(); Links wrapperOfLinks = new Links(linkCollection); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Link", wrapperOfLinks.toString()); // we can't encode the links in the body of the response, so we put them in the "Links:" header. httpHeaders.setLocation(URI.create(userResource.getLink("photo").getHref())); // "Location: /users/{userId}/photo" return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED); }
@RequestMapping(value = "/token_keys", method = RequestMethod.GET) @ResponseBody public ResponseEntity<VerificationKeysListResponse> getKeys(Principal principal, @RequestHeader(value = "If-None-Match", required = false, defaultValue = "NaN") String eTag) { String lastModified = ((Long) IdentityZoneHolder.get().getLastModified().getTime()).toString(); if (unmodifiedResource(eTag, lastModified)) { return new ResponseEntity<>(HttpStatus.NOT_MODIFIED); } HttpHeaders header = new HttpHeaders(); header.put("ETag", Collections.singletonList(lastModified)); return new ResponseEntity<>(getKeys(principal), header, HttpStatus.OK); }
@RequestMapping(value = "/post", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public Mono<Map<String, Object>> postFormData(@RequestBody Mono<MultiValueMap<String, Part>> parts) { // StringDecoder decoder = StringDecoder.allMimeTypes(true); return parts.flux().flatMap(map -> Flux.fromIterable(map.values())) .flatMap(Flux::fromIterable) .filter(part -> part instanceof FilePart) .reduce(new HashMap<String, Object>(), (files, part) -> { MediaType contentType = part.headers().getContentType(); long contentLength = part.headers().getContentLength(); files.put(part.name(), "data:"+contentType+";base64,"+contentLength); //TODO: get part data return files; }).map(files -> Collections.singletonMap("files", files)); }
@RequestMapping(value = "", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public HttpHeaders create() throws URISyntaxException { HttpHeaders headers = new HttpHeaders(); headers.setLocation(new URI("/test/items/123")); return headers; }
@RequestMapping(value = "empty", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public HttpHeaders createNoHeader() { return new HttpHeaders(); } }
@RequestMapping("/httpHeaders") public void httpHeaders(@RequestHeader HttpHeaders headers, Writer writer) throws IOException { assertEquals("Invalid Content-Type", new MediaType("text", "html"), headers.getContentType()); multiValueMap(headers, writer); }
@Test public void testRequestToHeaderSettingHandler() throws Exception { URI url = new URI("http://localhost:" + this.port + "/header"); RequestEntity<Void> request = RequestEntity.get(url).build(); ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("bar", response.getHeaders().getFirst("foo")); }
@Test public void exchange() throws Exception { mockTextPlainHttpMessageConverter(); HttpHeaders requestHeaders = new HttpHeaders(); mockSentRequest(POST, "http://example.com", requestHeaders); mockResponseStatus(HttpStatus.OK); String expected = "42"; mockResponseBody(expected, MediaType.TEXT_PLAIN); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders); ResponseEntity<String> result = template.exchange("http://example.com", POST, entity, String.class); assertEquals("Invalid POST result", expected, result.getBody()); assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); verify(response).close(); }
@Test public void getForEntity() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); mockSentRequest(GET, "http://example.com", requestHeaders); mockTextPlainHttpMessageConverter(); mockResponseStatus(HttpStatus.OK); String expected = "Hello World"; mockTextResponseBody(expected); ResponseEntity<String> result = template.getForEntity("http://example.com", String.class); assertEquals("Invalid GET result", expected, result.getBody()); assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); assertEquals("Invalid Content-Type header", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); verify(response).close(); }
@Test public void postForEntity() throws Exception { mockTextPlainHttpMessageConverter(); HttpHeaders requestHeaders = new HttpHeaders(); mockSentRequest(POST, "http://example.com", requestHeaders); mockResponseStatus(HttpStatus.OK); String expected = "42"; mockResponseBody(expected, MediaType.TEXT_PLAIN); ResponseEntity<String> result = template.postForEntity("http://example.com", "Hello World", String.class); assertEquals("Invalid POST result", expected, result.getBody()); assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); verify(response).close(); }
@Test public void headersCopy() { HttpHeaders customHeaders = new HttpHeaders(); customHeaders.set("X-CustomHeader", "vale"); ResponseEntity<Void> responseEntity = ResponseEntity.ok().headers(customHeaders).build(); HttpHeaders responseHeaders = responseEntity.getHeaders(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertEquals(1, responseHeaders.size()); assertEquals(1, responseHeaders.get("X-CustomHeader").size()); assertEquals("vale", responseHeaders.getFirst("X-CustomHeader")); }