Java Code Examples for org.springframework.http.HttpHeaders#setContentType()
The following examples show how to use
org.springframework.http.HttpHeaders#setContentType() .
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: HeaderAssertionTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void doesNotExist() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HeaderAssertions assertions = headerAssertions(headers); // Success assertions.doesNotExist("Framework"); try { assertions.doesNotExist("Content-Type"); fail("Existing header expected"); } catch (AssertionError error) { Throwable cause = error.getCause(); assertNotNull(cause); assertEquals("Response header 'Content-Type' exists with " + "value=[application/json;charset=UTF-8]", cause.getMessage()); } }
Example 2
Source File: FormHttpMessageConverter.java From java-technology-stack with MIT License | 6 votes |
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException { final byte[] boundary = generateMultipartBoundary(); Map<String, String> parameters = new LinkedHashMap<>(2); if (!isFilenameCharsetSet()) { parameters.put("charset", this.charset.name()); } parameters.put("boundary", new String(boundary, StandardCharsets.US_ASCII)); MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters); HttpHeaders headers = outputMessage.getHeaders(); headers.setContentType(contentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> { writeParts(outputStream, parts, boundary); writeEnd(outputStream, boundary); }); } else { writeParts(outputMessage.getBody(), parts, boundary); writeEnd(outputMessage.getBody(), boundary); } }
Example 3
Source File: AdminServiceAPI.java From apollo with Apache License 2.0 | 6 votes |
public ReleaseDTO createRelease(String appId, Env env, String clusterName, String namespace, String releaseName, String releaseComment, String operator, boolean isEmergencyPublish) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("name", releaseName); parameters.add("comment", releaseComment); parameters.add("operator", operator); parameters.add("isEmergencyPublish", String.valueOf(isEmergencyPublish)); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(parameters, headers); ReleaseDTO response = restTemplate.post( env, "apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases", entity, ReleaseDTO.class, appId, clusterName, namespace); return response; }
Example 4
Source File: RestTemplateBasicLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void givenFooService_whenFormSubmit_thenResourceIsCreated() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("id", "1"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class); assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); final String fooResponse = response.getBody(); assertThat(fooResponse, notNullValue()); assertThat(fooResponse, is("1")); }
Example 5
Source File: AdminCollectionController.java From tds with BSD 3-Clause "New" or "Revised" License | 6 votes |
@RequestMapping(value = {"/" + SHOW_CSV}) protected ResponseEntity<String> showCollectionStatusCsv() throws Exception { Formatter out = new Formatter(); // get sorted list of collections List<FeatureCollectionRef> fcList = dataRootManager.getFeatureCollections(); Collections.sort(fcList, (o1, o2) -> { int compareType = o1.getConfig().type.toString().compareTo(o1.getConfig().type.toString()); if (compareType != 0) return compareType; return o1.getCollectionName().compareTo(o2.getCollectionName()); }); out.format("%s, %s, %s, %s, %s, %s, %s, %s, %s%n", "collection", "ed", "type", "group", "nrecords", "ndups", "%", "nmiss", "%"); for (FeatureCollectionRef fc : fcList) { if (fc.getConfig().type != FeatureCollectionType.GRIB1 && fc.getConfig().type != FeatureCollectionType.GRIB2) continue; InvDatasetFeatureCollection fcd = datasetManager.openFeatureCollection(fc); out.format("%s", fcd.showStatusShort("csv")); } HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>(out.toString(), responseHeaders, HttpStatus.OK); }
Example 6
Source File: AttachmentApiController.java From onboard with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/pdf/{attachmentId}", method = RequestMethod.GET) @Interceptors({ ProjectMemberRequired.class }) @ResponseBody public HttpEntity<byte[]> renderPDFInPage(@PathVariable("companyId") int companyId, @PathVariable("projectId") int projectId, @PathVariable("attachmentId") int attachmentId) throws UnsupportedEncodingException { Attachment attachment = attachmentService.getById(attachmentId); byte[] bytes = attachmentService.getAttachmentContentById(projectId, attachmentId); if (attachment == null || bytes == null) { throw new ResourceNotFoundException(); } HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.parseMediaType("application/pdf")); String filename = new String(attachment.getName().getBytes("GB2312"), "ISO_8859_1"); header.setContentDispositionFormData("attachment", filename); header.add("X-Accel-Redirect", String.format("/attachments/%d/%d", projectId, attachmentId)); header.add("X-Accel-Charset", "utf-8"); return new HttpEntity<byte[]>(bytes, header); }
Example 7
Source File: SpringHttpMessageConvertersLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void givenConsumingXml_whenWritingTheFoo_thenCorrect() { final String URI = BASE_URI + "foos/{id}"; final RestTemplate restTemplate = new RestTemplate(); final Foo resource = new Foo(4, "jason"); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType((MediaType.APPLICATION_XML)); final HttpEntity<Foo> entity = new HttpEntity<Foo>(resource, headers); final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.PUT, entity, Foo.class, resource.getId()); final Foo fooResponse = response.getBody(); Assert.assertEquals(resource.getId(), fooResponse.getId()); }
Example 8
Source File: HttpSyncDataService.java From soul with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private void doLongPolling() { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); for (ConfigGroupEnum group : ConfigGroupEnum.values()) { ConfigData<?> cacheConfig = GROUP_CACHE.get(group); String value = String.join(",", cacheConfig.getMd5(), String.valueOf(cacheConfig.getLastModifyTime())); params.put(group.name(), Lists.newArrayList(value)); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity httpEntity = new HttpEntity(params, headers); for (String server : serverList) { String listenerUrl = server + "/configs/listener"; log.debug("request listener configs: [{}]", listenerUrl); try { String json = this.httpClient.postForEntity(listenerUrl, httpEntity, String.class).getBody(); log.debug("listener result: [{}]", json); JsonArray groupJson = GSON.fromJson(json, JsonObject.class).getAsJsonArray("data"); if (groupJson != null) { // fetch group configuration async. ConfigGroupEnum[] changedGroups = GSON.fromJson(groupJson, ConfigGroupEnum[].class); if (ArrayUtils.isNotEmpty(changedGroups)) { log.info("Group config changed: {}", Arrays.toString(changedGroups)); this.fetchGroupConfig(changedGroups); } } break; } catch (RestClientException e) { log.error("listener configs fail, can not connection this server:[{}]", listenerUrl); /* ex = new SoulException("Init cache error, serverList:" + serverList, e);*/ // try next server, if have another one. } } }
Example 9
Source File: CommonUtils.java From WeBASE-Front with Apache License 2.0 | 5 votes |
/** * set HttpHeaders. * * @return */ public static HttpHeaders buildHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); return headers; }
Example 10
Source File: SourceDaoImpl.java From singleton with Eclipse Public License 2.0 | 5 votes |
@Override public boolean sendToRemote(String url, Map<String, Object> requestParam) { LOGGER.info("Send data to remote server [{}] ...", url); LOGGER.info("The request body is: {}", requestParam); boolean result = false; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType .parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); JSONObject jsonObj = new JSONObject(requestParam); HttpEntity<String> formEntity = new HttpEntity<String>( jsonObj.toString(), headers); try { ResponseEntity<GRMResponseDTO> responseEntity = restTemplate .postForEntity(url, formEntity, GRMResponseDTO.class); GRMResponseDTO gRMResponseDTO = responseEntity.getBody(); if (gRMResponseDTO.getStatus() == GRMAPIResponseStatus.CREATED .getCode()) { result = true; LOGGER.info("The request has successed, the result: {} {}", gRMResponseDTO.getStatus(), gRMResponseDTO.getResult()); } else { LOGGER.info("The request has failed, the response code: {} reason: {}", + gRMResponseDTO.getStatus(), gRMResponseDTO.getErrorMessage()); } } catch (Exception e) { result = false; } return result; }
Example 11
Source File: HipchatNotifier.java From Moss with Apache License 2.0 | 5 votes |
protected HttpEntity<Map<String, Object>> createHipChatNotification(InstanceEvent event, Instance instance) { Map<String, Object> body = new HashMap<>(); body.put("color", getColor(event)); body.put("message", getMessage(event, instance)); body.put("notify", getNotify()); body.put("message_format", "html"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(body, headers); }
Example 12
Source File: AbstractRequestMappingIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
<T> ResponseEntity<T> performPost(String url, MediaType in, Object body, MediaType out, ParameterizedTypeReference<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 13
Source File: LetsChatNotifier.java From spring-boot-admin with Apache License 2.0 | 5 votes |
@Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // Let's Chat requiers the token as basic username, the password can be an // arbitrary string. String auth = Base64Utils .encodeToString(String.format("%s:%s", token, username).getBytes(StandardCharsets.UTF_8)); headers.add(HttpHeaders.AUTHORIZATION, String.format("Basic %s", auth)); return Mono.fromRunnable(() -> restTemplate.exchange(createUrl(), HttpMethod.POST, new HttpEntity<>(createMessage(event, instance), headers), Void.class)); }
Example 14
Source File: RadarServerController.java From tds with BSD 3-Clause "New" or "Revised" License | 5 votes |
@RequestMapping(value = "catalog.xml") @ResponseBody public HttpEntity<byte[]> topLevelCatalog() throws IOException { if (!enabled) return null; String URLbase = tdsContext.getContextPath() + "/" + entryPoint; CatalogBuilder cb = new CatalogBuilder(); cb.addService(new Service("radarServer", URLbase, "QueryCapability", null, null, new ArrayList<Service>(), new ArrayList<Property>(), null)); cb.setName("THREDDS Radar Server"); DatasetBuilder mainDB = new DatasetBuilder(null); mainDB.setName("Radar Data"); for (Map.Entry<String, RadarDataInventory> ent : data.entrySet()) { RadarDataInventory di = ent.getValue(); CatalogRefBuilder crb = new CatalogRefBuilder(mainDB); crb.setName(di.getName()); crb.setTitle(di.getName()); crb.setHref(ent.getKey() + "/dataset.xml"); mainDB.addDataset(crb); } cb.addDataset(mainDB); CatalogXmlWriter writer = new CatalogXmlWriter(); ByteArrayOutputStream os = new ByteArrayOutputStream(10000); writer.writeXML(cb.makeCatalog(), os); byte[] xmlBytes = os.toByteArray(); HttpHeaders header = new HttpHeaders(); header.setContentType(new MediaType("application", "xml")); header.setContentLength(xmlBytes.length); return new HttpEntity<>(xmlBytes, header); }
Example 15
Source File: RestUserControllerTest.java From Spring with Apache License 2.0 | 5 votes |
@Test public void createUser() { final User user = new User(); user.setEmail("[email protected]"); user.setUsername("doctorwho"); user.setLastName("Doctor"); user.setFirstName("Who"); user.setRating(0d); user.setActive(true); user.setPassword("what"); user.setUserType(UserType.ADMIN); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); final HttpEntity<User> crRequest = new HttpEntity<>(user, headers); final URI uri = this.restTemplate.postForLocation(GET_POST_URL, crRequest, User.class); System.out.println(">> Location for new user: " + uri); assertNotNull(uri); assertTrue(uri.toString().contains("doctorwho")); // test insertion final User newUser = restTemplate.getForObject(uri, User.class); assertNotNull(newUser); assertNotNull(newUser.getId()); }
Example 16
Source File: RestDesformUtil.java From jeecg-boot with Apache License 2.0 | 5 votes |
private static HttpHeaders getHeaders(String token) { HttpHeaders headers = new HttpHeaders(); String mediaType = MediaType.APPLICATION_JSON_UTF8_VALUE; headers.setContentType(MediaType.parseMediaType(mediaType)); headers.set("Accept", mediaType); headers.set("X-Access-Token", token); return headers; }
Example 17
Source File: BookingControllerIntegrationTests.java From Microservices-Building-Scalable-Software with MIT License | 4 votes |
/** * Test the POST /v1/booking API * * @throws JsonProcessingException */ @Test public void testAdd() throws JsonProcessingException { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("name", "TestBkng 3"); requestBody.put("id", "3"); requestBody.put("userId", "3"); requestBody.put("restaurantId", "1"); requestBody.put("tableId", "1"); LocalDate nowDate = LocalDate.now(); LocalTime nowTime = LocalTime.now(); requestBody.put("date", nowDate); requestBody.put("time", nowTime); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); objectMapper.findAndRegisterModules(); HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers); ResponseEntity<Map> responseE = restTemplate.exchange("http://localhost:" + port + "/v1/booking", HttpMethod.POST, entity, Map.class, Collections.EMPTY_MAP); assertNotNull(responseE); // Should return created (status code 201) assertEquals(HttpStatus.CREATED, responseE.getStatusCode()); //validating the newly created booking using API call Map<String, Object> response = restTemplate.getForObject("http://localhost:" + port + "/v1/booking/3", Map.class); assertNotNull(response); //Asserting API Response String id = response.get("id").toString(); assertNotNull(id); assertEquals("3", id); String name = response.get("name").toString(); assertNotNull(name); assertEquals("TestBkng 3", name); boolean isModified = (boolean) response.get("isModified"); assertEquals(false, isModified); String userId = response.get("userId").toString(); assertNotNull(userId); assertEquals("3", userId); String restaurantId = response.get("restaurantId").toString(); assertNotNull(restaurantId); assertEquals("1", restaurantId); String tableId = response.get("tableId").toString(); assertNotNull(tableId); assertEquals("1", tableId); String date1 = response.get("date").toString(); assertNotNull(date1); String[] arrDate = date1.replace("[", "").replace("]", "").split(","); assertEquals(nowDate, LocalDate.of(Integer.parseInt(arrDate[0].trim()), Integer.parseInt(arrDate[1].trim()), Integer.parseInt(arrDate[2].trim()))); String time1 = response.get("time").toString(); assertNotNull(time1); String[] arrTime = time1.replace("[", "").replace("]", "").split(","); assertEquals(nowTime, LocalTime.of(Integer.parseInt(arrTime[0].trim()), Integer.parseInt(arrTime[1].trim()), Integer.parseInt(arrTime[2].trim()), Integer.parseInt(arrTime[3].trim()))); }
Example 18
Source File: RestaurantControllerIntegrationTests.java From Mastering-Microservices-with-Java-Third-Edition with MIT License | 4 votes |
/** * Test the POST /v1/restaurants API */ @Test public void testAdd() throws JsonProcessingException { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("name", "La Plaza Restaurant"); requestBody.put("id", "11"); requestBody.put("address", "address of La Plaza Restaurant"); Map<String, Object> table1 = new HashMap<>(); table1.put("name", "Table 1"); table1.put("id", BigInteger.ONE); table1.put("capacity", Integer.valueOf(6)); Map<String, Object> table2 = new HashMap<>(); table2.put("name", "Table 2"); table2.put("id", BigInteger.valueOf(2)); table2.put("capacity", Integer.valueOf(4)); Map<String, Object> table3 = new HashMap<>(); table3.put("name", "Table 3"); table3.put("id", BigInteger.valueOf(3)); table3.put("capacity", Integer.valueOf(2)); List<Map<String, Object>> tableList = new ArrayList(); tableList.add(table1); tableList.add(table2); tableList.add(table3); requestBody.put("tables", tableList); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers); ResponseEntity<Map> responseE = restTemplate .exchange("http://localhost:" + port + "/v1/restaurants", HttpMethod.POST, entity, Map.class, Collections.EMPTY_MAP); assertNotNull(responseE); // Should return created (status code 201) assertEquals(HttpStatus.CREATED, responseE.getStatusCode()); //validating the newly created restaurant using API call Map<String, Object> response = restTemplate.getForObject("http://localhost:" + port + "/v1/restaurants/11", Map.class); assertNotNull(response); //Asserting API Response String id = response.get("id").toString(); assertNotNull(id); assertEquals("11", id); String name = response.get("name").toString(); assertNotNull(name); assertEquals("La Plaza Restaurant", name); String address = response.get("address").toString(); assertNotNull(address); assertEquals("address of La Plaza Restaurant", address); boolean isModified = (boolean) response.get("isModified"); assertEquals(false, isModified); List<Map<String, Object>> tableList2 = (List<Map<String, Object>>) response.get("tables"); assertNotNull(tableList2); assertEquals(tableList2.size(), 3); tableList2.stream().forEach((table) -> { assertNotNull(table); assertNotNull(table.get("name")); assertNotNull(table.get("id")); assertTrue((Integer) table.get("capacity") > 0); }); }
Example 19
Source File: BookingControllerIntegrationTests.java From Microservices-Building-Scalable-Software with MIT License | 4 votes |
/** * Test the POST /v1/booking API * * @throws JsonProcessingException */ @Test public void testAdd() throws JsonProcessingException { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("userId", "3"); requestBody.put("restaurantId", "1"); requestBody.put("tableId", "1"); LocalDate nowDate = LocalDate.now(); LocalTime nowTime = LocalTime.now(); requestBody.put("date", nowDate); requestBody.put("time", nowTime); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); objectMapper.findAndRegisterModules(); HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers); ResponseEntity<Map> responseE = restTemplate.exchange("http://localhost:" + port + "/v1/booking", HttpMethod.POST, entity, Map.class, Collections.EMPTY_MAP); assertNotNull(responseE); // Should return created (status code 201) assertEquals(HttpStatus.CREATED, responseE.getStatusCode()); //validating the newly created booking using API call Map<String, Object> response = restTemplate.getForObject("http://localhost:" + port + "/v1/booking/3", Map.class); assertNotNull(response); //Asserting API Response String id = response.get("id").toString(); assertNotNull(id); assertEquals("3", id); String name = response.get("name").toString(); assertNotNull(name); assertEquals("Booking ".concat(id), name); boolean isModified = (boolean) response.get("isModified"); assertEquals(false, isModified); String userId = response.get("userId").toString(); assertNotNull(userId); assertEquals("3", userId); String restaurantId = response.get("restaurantId").toString(); assertNotNull(restaurantId); assertEquals("1", restaurantId); String tableId = response.get("tableId").toString(); assertNotNull(tableId); assertEquals("1", tableId); String date1 = response.get("date").toString(); assertNotNull(date1); String[] arrDate = date1.split("-"); assertEquals(nowDate, LocalDate.of(Integer.parseInt(arrDate[0].trim()), Integer.parseInt(arrDate[1].trim()), Integer.parseInt(arrDate[2].trim()))); String time1 = response.get("time").toString(); assertNotNull(time1); String[] arrTime = time1.split(":"); int dotIndex = arrTime[2].indexOf("."); String seconds = arrTime[2].substring(0, dotIndex); String strMilliSeconds = arrTime[2].substring(dotIndex + 1); int milliSeconds = Double.valueOf(Double.valueOf(strMilliSeconds.trim()).doubleValue() * 1000000D).intValue(); assertEquals(nowTime, LocalTime.of(Integer.parseInt(arrTime[0].trim()), Integer.parseInt(arrTime[1].trim()), Integer.parseInt(seconds.trim()), milliSeconds)); }
Example 20
Source File: ContaAzulService.java From api-examples with Apache License 2.0 | 4 votes |
private HttpHeaders getTokenRequestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", getBasicAuthenticationHeader()); return headers; }