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

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

@Test
public void shouldPassAuthenticatedCorsRequest() {
  // given
  // cross origin but allowed through wildcard
  String origin = "http://other.origin";

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.ORIGIN, origin);

  Group group = new GroupEntity("groupId");
  
  // create group
  processEngine.getIdentityService().saveGroup(new GroupEntity("groupId"));

  group.setName("updatedGroupName");

  // when
  ResponseEntity<String> response = authTestRestTemplate.exchange(CONTEXT_PATH + "/group/" + group.getId(), HttpMethod.PUT, new HttpEntity<>(group, headers),
      String.class);

  // then
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
  assertThat(response.getHeaders().getAccessControlAllowOrigin()).contains("*");
}
 
源代码2 项目: Moss   文件: MicrosoftTeamsNotifierTest.java
@Test
@SuppressWarnings("unchecked")
public void test_onClientApplicationDeRegisteredEvent_resolve() {
    InstanceDeregisteredEvent event = new InstanceDeregisteredEvent(instance.getId(), 1L);

    StepVerifier.create(notifier.doNotify(event, instance)).verifyComplete();

    ArgumentCaptor<HttpEntity<Message>> entity = ArgumentCaptor.forClass(HttpEntity.class);
    verify(mockRestTemplate).postForEntity(eq(URI.create("http://example.com")),
        entity.capture(),
        eq(Void.class)
    );

    assertThat(entity.getValue().getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
    assertMessage(entity.getValue().getBody(),
        notifier.getDeRegisteredTitle(),
        notifier.getMessageSummary(),
        String.format(notifier.getDeregisterActivitySubtitlePattern(),
            instance.getRegistration().getName(),
            instance.getId()
        )
    );
}
 
源代码3 项目: MicroCommunity   文件: AddStaffServiceListener.java
/**
 * 用户赋权
 *
 * @return
 */
private void privilegeUserDefault(DataFlowContext dataFlowContext, JSONObject paramObj) {
    ResponseEntity responseEntity = null;
    AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
    if (appService == null) {
        responseEntity = new ResponseEntity<String>("当前没有权限访问" + ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE, HttpStatus.UNAUTHORIZED);
        dataFlowContext.setResponseEntity(responseEntity);
        return;
    }
    String requestUrl = appService.getUrl();
    HttpHeaders header = new HttpHeaders();
    header.add(CommonConstant.HTTP_SERVICE.toLowerCase(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
    userBMOImpl.freshHttpHeader(header, dataFlowContext.getRequestCurrentHeaders());
    JSONObject paramInObj = new JSONObject();
    paramInObj.put("userId", paramObj.getString("userId"));
    paramInObj.put("storeTypeCd", paramObj.getString("storeTypeCd"));
    paramInObj.put("userFlag", "staff");
    HttpEntity<String> httpEntity = new HttpEntity<String>(paramInObj.toJSONString(), header);
    doRequest(dataFlowContext, appService, httpEntity);
    responseEntity = dataFlowContext.getResponseEntity();

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        dataFlowContext.setResponseEntity(responseEntity);
    }
}
 
@Test
@SuppressWarnings("unchecked")
public void bulkRegenerate() {
	Map<String, List<CredentialName>> expectedResponse = Collections.singletonMap(
			CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD,
			Arrays.asList(new SimpleCredentialName("example-certificate1"),
					new SimpleCredentialName("example-certificate2")));

	Map<String, Object> request = new HashMap<String, Object>() {
		{
			put(CredHubCertificateTemplate.SIGNED_BY_REQUEST_FIELD, NAME.getName());
		}
	};

	given(this.restTemplate.exchange(eq(CredHubCertificateTemplate.BULK_REGENERATE_URL_PATH), eq(HttpMethod.POST),
			eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class)))
					.willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK));

	List<CredentialName> response = this.credHubTemplate.regenerate(NAME);

	assertThat(response).isNotNull();
	assertThat(response)
			.isEqualTo(expectedResponse.get(CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD));
}
 
/**
 * 本地没有公钥的时候,从服务器上获取
 * 需要进行 Basic 认证
 *
 * @return public key
 */
private String getKeyFromAuthorizationServer() {
    ObjectMapper objectMapper = new ObjectMapper();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
    HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
    String pubKey = new RestTemplate()
        .getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
    try {
        JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
        log.info("Get Key From Authorization Server.");
        return body.getStr("value");
    } catch (IOException e) {
        log.error("Get public key error: {}", e.getMessage());
    }
    return null;
}
 
@Test
public void ableToPostWithHeader() {
  Person person = new Person();
  person.setName("person name");

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(APPLICATION_JSON);
  headers.add("prefix", "prefix  prefix");

  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  for (String url : urls) {
    ResponseEntity<String> responseEntity = restTemplate
        .postForEntity(url + "saysomething", requestEntity, String.class);

    assertEquals("prefix  prefix person name", jsonBodyOf(responseEntity, String.class));
  }
}
 
@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
    String redirectUrl = "http://localhost:"+port+"/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
       + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
            + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());
    String location = response.getHeaders().get("Location").get(0);

    //FIXME: Is this a bug with redirect URL?
    location = location.replace("#", "?");

    response = new TestRestTemplate().getForEntity(location, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
 
源代码8 项目: DataLink   文件: WorkerController.java
@ResponseBody
@RequestMapping(value = "/doEditLogback")
public String saveLogback(String workerId, String content) {
    logger.info("Receive a request to save logback.xml, with workerId " + workerId + "\r\n with content " + content);

    if (StringUtils.isBlank(content)) {
        return "content can not be null";
    }
    try {
        WorkerInfo workerInfo = workerService.getById(Long.valueOf(workerId));
        if (workerInfo != null) {
            String url = "http://" + workerInfo.getWorkerAddress() + ":" + workerInfo.getRestPort() + "/worker/doEditLogback/" + workerId;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, String> map = new HashMap<>();
            map.put("content", content);
            HttpEntity request = new HttpEntity(map, headers);
            new RestTemplate(Lists.newArrayList(new FastJsonHttpMessageConverter())).postForObject(url, request, String.class);
            return "success";
        }
        return "fail";
    } catch (Exception e) {
        logger.info("request to save logback.xml error:", e);
        return e.getMessage();
    }
}
 
源代码9 项目: spring-analysis-note   文件: RestTemplateTests.java
@Test
public void postForLocationEntityContentType() 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);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

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

	verify(response).close();
}
 
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void exchangeGetCallback() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("MyHeader", "MyValue");
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ListenableFuture<ResponseEntity<String>> responseFuture =
			template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
	responseFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
		@Override
		public void onSuccess(ResponseEntity<String> result) {
			assertEquals("Invalid content", helloWorld, result.getBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(responseFuture);
}
 
源代码11 项目: taskana   文件: TaskControllerIntTest.java
/**
 * TSK-926: If Planned and Due Date is provided to create a task and not matching to service level
 * throw an exception One is calculated by other other date +- service level.
 */
@Test
void testCreateWithPlannedAndDueDate() {
  TaskRepresentationModel taskRepresentationModel = getTaskResourceSample();
  Instant now = Instant.now();
  taskRepresentationModel.setPlanned(now);
  taskRepresentationModel.setDue(now);

  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_TASKS),
              HttpMethod.POST,
              new HttpEntity<>(taskRepresentationModel, restHelper.getHeadersUser_1_1()),
              TASK_MODEL_TYPE);
  assertThatThrownBy(httpCall).isInstanceOf(HttpClientErrorException.class);
}
 
private String getTaxUrlFromDestinationService() {
	try {
		final DestinationService destination = getDestinationServiceDetails("destination");
		final String accessToken = getOAuthToken(destination);
		headers.set("Authorization", "Bearer " + accessToken);
		HttpEntity entity = new HttpEntity(headers);
		final String taxUrl = destination.uri + DESTINATION_PATH + taxDestination;
		final ResponseEntity<String> response = restTemplate.exchange(taxUrl, HttpMethod.GET, entity, String.class);
		final JsonNode root = mapper.readTree(response.getBody());
		final String texDestination = root.path("destinationConfiguration").path("URL").asText();
		return texDestination;
	} catch (IOException e) {
		logger.error("No proper destination Service available: {}", e.getMessage());

	}
	return "";
}
 
private void testUpload() {
  BufferedInputStream bufferedInputStream0 = new BufferedInputStream(new ByteArrayInputStream("up0".getBytes()));
  BufferedInputStream bufferedInputStream1 = new BufferedInputStream(new ByteArrayInputStream("up1".getBytes()));
  BufferedInputStream bufferedInputStream2 = new BufferedInputStream(new ByteArrayInputStream("up2".getBytes()));

  HashMap<String, Object> formData = new HashMap<>();
  formData.put("up0", bufferedInputStream0);
  formData.put("up1", bufferedInputStream1);
  formData.put("up2", bufferedInputStream2);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  HttpEntity<Map<String, Object>> entity = new HttpEntity<>(formData, headers);

  String result = restTemplate.postForObject("cse://jaxrs/beanParamTest/upload?query=fromTemplate&extraQuery=ex",
      entity,
      String.class);
  TestMgr.check(
      "testBeanParameter=TestBeanParameterWithUpload{queryStr='fromTemplate'}|extraQuery=ex|up0=up0|up1=up1|up2=up2",
      result);
}
 
源代码14 项目: jVoiD   文件: HomeController.java
@RequestMapping("/order")
public @ResponseBody String orderProductNowById(@RequestParam("cartId") String cartId, @RequestParam("prodId") String productId) {
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

	JSONObject jsonObj = new JSONObject();
	try {
		jsonObj.put("cartId", Integer.parseInt(cartId));
		jsonObj.put("productId", Integer.parseInt(productId));
		jsonObj.put("attributeId", 1);
		jsonObj.put("quantity", 1);
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	System.out.println("param jsonObj=>"+jsonObj.toString());
	
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ServerUris.QUOTE_SERVER_URI+URIConstants.ADD_PRODUCT_TO_CART)
	        .queryParam("params", jsonObj);	
	HttpEntity<?> entity = new HttpEntity<>(headers);
	HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class);
	return returnString.getBody();
}
 
源代码15 项目: SkaETL   文件: MetricImporter.java
private void sendToRegistry(String action) {
    if (registryConfiguration.getActive()) {
        RegistryWorker registry = null;
        try {
            registry = RegistryWorker.builder()
                    .workerType(WorkerType.METRIC_PROCESS)
                    .ip(InetAddress.getLocalHost().getHostName())
                    .name(InetAddress.getLocalHost().getHostName())
                    .port(processConfiguration.getPortClient())
                    .statusConsumerList(statusExecutor())
                    .build();
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<RegistryWorker> request = new HttpEntity<>(registry);
            String url = processConfiguration.getUrlRegistry();
            String res = restTemplate.postForObject(url + "/process/registry/" + action, request, String.class);
            log.debug("sendToRegistry result {}", res);
        } catch (Exception e) {
            log.error("Exception on sendToRegistry", e);
        }
    }
}
 
@HystrixCommand(fallbackMethod="getDefaultIngredients",
    commandProperties={
        @HystrixProperty(
            name="execution.isolation.thread.timeoutInMilliseconds",
            value="500"),
            @HystrixProperty(
                name="circuitBreaker.requestVolumeThreshold",
                value="30"),
            @HystrixProperty(
                name="circuitBreaker.errorThresholdPercentage",
                value="25"),
            @HystrixProperty(
                name="metrics.rollingStats.timeInMilliseconds",
                value="20000"),
            @HystrixProperty(
                name="circuitBreaker.sleepWindowInMilliseconds",
                value="60000")
    })
public Iterable<Ingredient> getAllIngredients() {
  ParameterizedTypeReference<List<Ingredient>> stringList =
      new ParameterizedTypeReference<List<Ingredient>>() {};
  return rest.exchange(
      "http://ingredient-service/ingredients", HttpMethod.GET,
      HttpEntity.EMPTY, stringList).getBody();
}
 
@Test
public void testCmmnRestApiIntegrationWithAuthentication() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/cmmn-api/cmmn-repository/case-definitions";

    HttpEntity<?> request = new HttpEntity<>(createHeaders("filiphr", "password"));
    ResponseEntity<DataResponse<CaseDefinitionResponse>> response = restTemplate
        .exchange(processDefinitionsUrl, HttpMethod.GET, request, new ParameterizedTypeReference<DataResponse<CaseDefinitionResponse>>() {
        });

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<CaseDefinitionResponse> caseDefinitions = response.getBody();
    assertThat(caseDefinitions).isNotNull();
    CaseDefinitionResponse defResponse = caseDefinitions.getData().get(0);
    assertThat(defResponse.getKey()).isEqualTo("case1");
    assertThat(defResponse.getUrl()).startsWith("http://localhost:" + serverPort + "/cmmn-api/cmmn-repository/case-definitions/");
}
 
源代码18 项目: onboard   文件: AttachmentApi.java
@RequestMapping(value = "/api/{companyId}/projects/{projectId}/attachments/{attachmentId}/download", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> downloadAttachment(@PathVariable("companyId") int companyId,
        @PathVariable("projectId") int projectId, @PathVariable("attachmentId") int attachmentId, HttpServletRequest request)
        throws IOException {
    String byteUri = String.format(ATTACHMENT_BYTE, companyId, projectId, attachmentId);
    String attachmentUri = String.format(ATTACHMENT_ID, companyId, projectId, attachmentId);
    byte[] bytes = netService.getForObject(byteUri, byte[].class);
    AttachmentDTO attachment = netService.getForObject(attachmentUri, AttachmentDTO.class);
    if (attachment == null || bytes == null) {
        throw new com.onboard.frontend.exception.ResourceNotFoundException();
    }
    HttpHeaders header = new HttpHeaders();
    String filename = new String(attachment.getName().getBytes("GB2312"), "ISO_8859_1");
    header.setContentDispositionFormData("attachment", filename);
    return new HttpEntity<byte[]>(bytes, header);
}
 
@Test
public void handleHttpEntity() throws Exception {
	Class<?>[] parameterTypes = new Class<?>[] {HttpEntity.class};

	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.setContent("Hello Server".getBytes("UTF-8"));

	HandlerMethod handlerMethod = handlerMethod("handleHttpEntity", parameterTypes);

	ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod);

	assertNull(mav);
	assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus());
	assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8"));
	assertEquals("headerValue", response.getHeader("header"));
	// set because of @SesstionAttributes
	assertEquals("no-store", response.getHeader("Cache-Control"));
}
 
源代码20 项目: WeEvent   文件: RestfulTest.java
@Test
public void testPublishContentIs10K() {
    MultiValueMap<String, String> eventData = new LinkedMultiValueMap<>();
    eventData.add("topic", this.topicName);
    eventData.add("content", get10KStr());

    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.APPLICATION_FORM_URLENCODED;
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(eventData, headers);
    ResponseEntity<SendResult> rsp = rest.postForEntity(url + "publish", request, SendResult.class);
    log.info("publish, status: " + rsp.getStatusCode() + " body: " + rsp.getBody());
    Assert.assertEquals(200, rsp.getStatusCodeValue());
    Assert.assertNotNull(rsp.getBody());
    Assert.assertTrue(rsp.getBody().getEventId().contains("-"));
}
 
@Test
public void shouldPassNonAuthenticatedPreflightRequest() {
  // given
  // cross origin but allowed through wildcard
  String origin = "http://other.origin";

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.HOST, "localhost");
  headers.add(HttpHeaders.ORIGIN, origin);
  headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name());
  headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, HttpHeaders.ORIGIN);

  // when
  ResponseEntity<String> response = testRestTemplate.exchange(CONTEXT_PATH + "/task", HttpMethod.OPTIONS, new HttpEntity<>(headers), String.class);

  // then
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
源代码22 项目: java-technology-stack   文件: RestTemplateTests.java
@Test
public void postForLocationEntityContentType() throws Exception {
	mockSentRequest(POST, "http://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);

	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("http://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

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

	verify(response).close();
}
 
源代码23 项目: Moss   文件: LetsChatNotifierTest.java
@Test
public void test_onApplicationEvent_resolve_with_custom_message() {
    notifier.setMessage("TEST");
    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown())))
                .verifyComplete();
    clearInvocations(restTemplate);

    StepVerifier.create(
        notifier.notify(new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofUp())))
                .verifyComplete();

    HttpEntity<?> expected = expectedMessage("TEST");
    verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))),
        eq(HttpMethod.POST), eq(expected), eq(Void.class));
}
 
源代码24 项目: api-layer   文件: StaticAPIService.java
private HttpEntity<?> getHttpEntity(String discoveryServiceUrl) {
    boolean isHttp = discoveryServiceUrl.startsWith("http://");
    HttpHeaders httpHeaders = new HttpHeaders();
    if (isHttp) {
        String basicToken = "Basic " + Base64.getEncoder().encodeToString((eurekaUserid + ":" + eurekaPassword).getBytes());
        httpHeaders.add("Authorization", basicToken);
    }

    return new HttpEntity<>(null, httpHeaders);
}
 
@Test
public void httpEntityWithCompletableFutureBody() throws Exception {
	ServerWebExchange exchange = postExchange("line1");
	ResolvableType type = httpEntityType(CompletableFuture.class, String.class);
	HttpEntity<CompletableFuture<String>> httpEntity = resolveValue(exchange, type);

	assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
	assertEquals("line1", httpEntity.getBody().get());
}
 
源代码26 项目: taskana   文件: WorkbasketControllerIntTest.java
@Test
void testMarkWorkbasketForDeletionAsBusinessAdminWithoutExplicitReadPermission() {

  String workbasketID = "WBI:100000000000000000000000000000000005";

  ResponseEntity<?> response =
      TEMPLATE.exchange(
          restHelper.toUrl(Mapping.URL_WORKBASKET_ID, workbasketID),
          HttpMethod.DELETE,
          new HttpEntity<>(restHelper.getHeadersBusinessAdmin()),
          Void.class);
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
}
 
源代码27 项目: Mastering-Spring-5.0   文件: TodoControllerIT.java
@Test
public void retrieveTodos() throws Exception {
	String expected = "[" + "{id:1,user:Jack,desc:\"Learn Spring MVC\",done:false}" + ","
			+ "{id:2,user:Jack,desc:\"Learn Struts\",done:false}" + "]";
	
	ResponseEntity<String> response = template.exchange(
	           createUrl("/users/Jack/todos"), HttpMethod.GET,
	             new HttpEntity<String>(null, headers),
	               String.class);

	JSONAssert.assertEquals(expected, response.getBody(), false);
}
 
源代码28 项目: docs-manage   文件: PostController.java
@PutMapping("/docs/{postId}")
public Result updatePost(@PathVariable Long postId, @RequestBody PostUpdate postUpdate) {
    String url = DocsConsts.DOCS_SERVER_HOST + "/docs/{postId}";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    HttpEntity<PostUpdate> entity = new HttpEntity<>(postUpdate, headers);
    return restTemplate.exchange(url, HttpMethod.PUT, entity, Result.class, postId).getBody();
}
 
源代码29 项目: zstack   文件: SftpBackupStorageSimulator.java
@RequestMapping(value = SftpBackupStorageConstant.DOWNLOAD_IMAGE_PATH, method = RequestMethod.POST)
public
@ResponseBody
String download(HttpServletRequest req) throws InterruptedException {
    HttpEntity<String> entity = restf.httpServletRequestToHttpEntity(req);
    if (!config.downloadSuccess1) {
        throw new CloudRuntimeException("Fail download on purpose");
    } else {
        doDownload(entity);
    }
    return null;
}
 
@Test  // SPR-12861
public void resolveArgumentWithEmptyBody() throws Exception {
	this.servletRequest.setContent(new byte[0]);
	this.servletRequest.setContentType("application/json");

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);

	HttpEntity<?> result = (HttpEntity<?>) processor.resolveArgument(this.paramSimpleBean,
			this.mavContainer, this.webRequest, this.binderFactory);

	assertNotNull(result);
	assertNull(result.getBody());
}
 
 类所在包
 同包方法