Issue
I have a controller that receives HttpServletRequest
with body form-data
with some key-value
I want to pass this HttpServletRequest
to another API. That another API controller receives HttpServletRequest
So far, I've tried this in my service 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.
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.
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);
Solution
Using RestTemplate::postForObject
and this class in general you have to pass the correct 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.
Note the HttpServletRequest
extends ServletRequest
.
- Extract body using either
ServletRequest::getInputStream
orServletRequest::getReader
. In case ofmultipart/form-data
useHttpServletRequest::getParts
- Serialize the bytes of body to an object that is required for
POST http:localhost:8080/save
. - Use the object and create
new HttpEntity(T body)
. - Pass it as
request
inside theRestTemplate::postForObject
method.
The exact steps might differ regarding what data you need, the point is you cannot pass HttpServletRequest
directly but use an instance of HttpEntity
.
Answered By - Nikolas Charalambidis
Answer Checked By - Senaida (JavaFixing Volunteer)