[英]Passing HttpServletRequest to another API controller
I have a controller that receives HttpServletRequest
with body form-data
with some key-value
我有一个 controller 接收带有一些
key-value
正文form-data
的HttpServletRequest
I want to pass this HttpServletRequest
to another API.我想将此
HttpServletRequest
传递给另一个 API。 That another API controller receives HttpServletRequest
另一个 API controller 收到
HttpServletRequest
So far, I've tried this in my service class.到目前为止,我已经在我的服务 class 中尝试过这个。
public void saveApi(HttpServletRequest request) throws Exception {
System.out.println(request.getCode());
RestTemplate restTemplate = new RestTemplate();
HttpServletRequest result = restTemplate.postForObject( "http:localhost:8080/save", request, HttpServletRequest .class);
}
The result is the other API java.lang.NullPointerException: null
, other API didn't receive my post.结果是另一个 API
java.lang.NullPointerException: null
,其他 ZDB97442387143ACE143 没有收到我的帖子。
How to do that?怎么做? Is it possible?
可能吗?
Another service, for example: GET
method, I use the RestTemplate
to call to another API with some parameter, it succeeds.另一个服务,例如:
GET
方法,我使用RestTemplate
调用另一个 API 并带有一些参数,它成功。
UPDATE更新
the answer is:答案是:
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("name", request.getParameter("name"));
form.add("blabla", request.getParameter("blabla"));
form.add("blabla", request.getParameter("blabla"));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, httpHeaders);
restTemplate.postForEntity("http:localhost:8080/save", requestEntity, String.class);
Using RestTemplate::postForObject
and this class in general you have to pass the correct request
object:使用
RestTemplate::postForObject
和这个 class 通常你必须传递正确的request
object:
The request parameter can be a HttpEntity in order to add additional HTTP headers to the request, that is
HttpEntity
with body and headers.请求参数可以是 HttpEntity,以便向请求添加额外的 HTTP 标头,即带有正文和标头的
HttpEntity
。
Note the HttpServletRequest
extends ServletRequest
.注意
HttpServletRequest
扩展了ServletRequest
。
ServletRequest::getInputStream
or ServletRequest::getReader
.ServletRequest::getInputStream
或ServletRequest::getReader
提取正文。 In case of multipart/form-data
use HttpServletRequest::getParts
multipart/form-data
,请使用HttpServletRequest::getParts
POST http:localhost:8080/save
.POST http:localhost:8080/save
所需的 object。new HttpEntity(T body)
.new HttpEntity(T body)
。request
inside the RestTemplate::postForObject
method.RestTemplate::postForObject
方法中将其作为request
传递。 The exact steps might differ regarding what data you need, the point is you cannot pass HttpServletRequest
directly but use an instance of HttpEntity
.关于您需要的数据,确切的步骤可能会有所不同,关键是您不能直接传递
HttpServletRequest
而是使用HttpEntity
的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.