org.springframework.http.HttpEntity#getBody ( )源码实例Demo

下面列出了org.springframework.http.HttpEntity#getBody ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: 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();
}
 
private Mono<Object> doHttpRequest(HttpRequestNode<Object> step, Object state) {

		HttpRequest<Object> definition = step.getDefinition();
		HttpEntity<?> entity = getEntity(definition.getEntity(), state);

		RequestBodySpec spec;
		if (definition.getUri() == null) {

			spec = this.webClient.method(definition.getMethod()).uri(definition.getUriTemplate(),
					definition.getUrlVariables());
		}
		else {
			spec = this.webClient.method(definition.getMethod()).uri(definition.getUri());
		}

		for (Entry<String, List<String>> header : entity.getHeaders().entrySet()) {
			spec = spec.header(header.getKey(), header.getValue().get(0));
		}

		if (entity.getBody() != null && !entity.getBody().equals(Undefinded.INSTANCE)) {
			return spec.bodyValue(entity.getBody()).retrieve().bodyToMono(definition.getResponseType());
		}

		return spec.retrieve().bodyToMono(definition.getResponseType());
	}
 
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	if (partBody == null) {
		throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
	}
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
源代码4 项目: jVoiD   文件: HomeController.java
@RequestMapping("/cart")
public @ResponseBody String getCartById(@RequestParam("cartId") String cartId) {
	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));
	} 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.GET_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();
}
 
源代码5 项目: onetwo   文件: FormHttpMessageConverter.java
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	if (partBody == null) {
		throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
	}
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	if (partBody == null) {
		throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
	}
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
源代码7 项目: lams   文件: FormHttpMessageConverter.java
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
源代码8 项目: jVoiD   文件: UserAuthenticationProvider.java
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	
	// Make an API Call to the Customer WAR to get the user data based on this email address.
	//JSONObject user = userservice.getCustomerByEmail(username);
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
	
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI+URIConstants.GET_CUSTOMER_BY_EMAIL)
	        .queryParam("params", "{email: " + username + "}");	
	HttpEntity<?> entity = new HttpEntity<>(headers);
	HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class);
	
	SerializableJSONObject user = null;
	try {
		JSONObject temp = new JSONObject(returnString.getBody());
		user = new SerializableJSONObject(temp);
		System.out.println("User: " + user.toString());
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	if(user == null) {
		throw new UsernameNotFoundException(String.format("User %s not exist!", username));
	}
	
	return new UserRepositoryUserDetails(user);
}
 
@RequestMapping("/foo")
public ResponseEntity<String> foo(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
	assertNotNull(requestEntity);
	assertEquals("MyValue", requestEntity.getHeaders().getFirst("MyRequestHeader"));
	String requestBody = new String(requestEntity.getBody(), "UTF-8");
	assertEquals("Hello World", requestBody);

	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.set("MyResponseHeader", "MyValue");
	return new ResponseEntity<String>(requestBody, responseHeaders, HttpStatus.CREATED);
}
 
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}

	Object body = responseEntity.getBody();
	if (responseEntity instanceof ResponseEntity) {
		outputMessage.setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
		if (HttpMethod.GET == inputMessage.getMethod() && isResourceNotModified(inputMessage, outputMessage)) {
			outputMessage.setStatusCode(HttpStatus.NOT_MODIFIED);
			// Ensure headers are flushed, no body should be written.
			outputMessage.flush();
			// Skip call to converters, as they may update the body.
			return;
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(body, returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
@PostMapping("/foo")
public ResponseEntity<String> foo(HttpEntity<byte[]> requestEntity) throws Exception {
	assertNotNull(requestEntity);
	assertEquals("MyValue", requestEntity.getHeaders().getFirst("MyRequestHeader"));

	String body = new String(requestEntity.getBody(), "UTF-8");
	assertEquals("Hello World", body);

	URI location = new URI("/foo");
	return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body(body);
}
 
源代码12 项目: steady   文件: LibraryController.java
@RequestMapping(value = "/{digest}/upload", method = RequestMethod.POST, consumes = {"application/octet-stream"})
@JsonView(Views.LibDetails.class)
ResponseEntity<Library> postLibraryJAR(@PathVariable String digest, HttpEntity<byte[]> requestEntity) {
	LibraryController.log.info("Called postLibrary for JAR [" +digest+ "]");
	try {
		byte[] payload = requestEntity.getBody();
		InputStream inputStream = new ByteArrayInputStream(payload);

		if(!Files.exists(Paths.get(VulasConfiguration.getGlobal().getLocalM2Repository().toString()+ File.separator  +"uknownJars" ))){
			Files.createDirectories(Paths.get(VulasConfiguration.getGlobal().getLocalM2Repository().toString()+ File.separator  +"uknownJars" ));
		}

		String saveFilePath = VulasConfiguration.getGlobal().getLocalM2Repository().toString()+ File.separator  +"uknownJars" + File.separator + digest + ".jar";

		LibraryController.log.info("Saving JAR [" +digest+ "] to file [" + saveFilePath+"]");
		// opens an output stream to save into file
		FileOutputStream outputStream = new FileOutputStream(saveFilePath);

		int bytesRead = -1;
		byte[] buffer = new byte[inputStream.available()];
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		outputStream.close();

		inputStream.close();
		return new ResponseEntity<Library>(HttpStatus.OK);
	} catch (IOException e) {
		LibraryController.log.error("Error while saving the received JAR file [" + e + "]");
		return new ResponseEntity<Library>(HttpStatus.INTERNAL_SERVER_ERROR);
	}	     
}
 
源代码13 项目: spring-vault   文件: AuthenticationStepsExecutor.java
private static HttpEntity<?> getEntity(HttpEntity<?> entity, @Nullable Object state) {

		if (entity == null) {
			return state == null ? HttpEntity.EMPTY : new HttpEntity<>(state);
		}

		if (entity.getBody() == null && state != null) {
			return new HttpEntity<>(state, entity.getHeaders());
		}

		return entity;
	}
 
@PostMapping("/request/entity/mono")
public Mono<JacksonViewBean> entityMonoRequest(@JsonView(MyJacksonView1.class) HttpEntity<Mono<JacksonViewBean>> entityMono) {
	return entityMono.getBody();
}
 
源代码15 项目: secure-data-service   文件: RESTClientTest.java
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
    HttpEntity httpEntity = (HttpEntity) invocation.getArguments()[1];
    json = (String) httpEntity.getBody();
    return null;
}
 
源代码16 项目: spring-tutorial   文件: RequestDataController.java
@RequestMapping(value = "entity", method = RequestMethod.POST)
public @ResponseBody
String withEntity(HttpEntity<String> entity) {
	return "Posted request body '" + entity.getBody() + "'; headers = " + entity.getHeaders();
}
 
@PostMapping("/request/entity/mono")
public Mono<JacksonViewBean> entityMonoRequest(@JsonView(MyJacksonView1.class) HttpEntity<Mono<JacksonViewBean>> entityMono) {
	return entityMono.getBody();
}
 
@PostMapping("/request/entity/flux")
public Flux<JacksonViewBean> entityFluxRequest(@JsonView(MyJacksonView1.class) HttpEntity<Flux<JacksonViewBean>> entityFlux) {
	return entityFlux.getBody();
}
 
@RequestMapping
@ResponseBody
public JacksonViewBean handleHttpEntity(@JsonView(MyJacksonView1.class) HttpEntity<JacksonViewBean> entity) {
	return entity.getBody();
}
 
@RequestMapping
@ResponseBody
public JacksonViewBean handleHttpEntity(@JsonView(MyJacksonView1.class) HttpEntity<JacksonViewBean> entity) {
	return entity.getBody();
}