I want to send a post request in java.
I have seen examples for the post request by using Http Client.
But i want use sendRedirect method.
For ex,
https://processthis.com/process?name=xyz&phone=9898989898
I want to use post request to send those parameters. So, those params will not be visible to any one and at the same time i need to redirect my url to that url as,
response.sendRedirect("https://processthis.com/process");
According to RFC2616 with HTTP/1.1 you can send 307 response code, which will make user-agent
to repeat it's POST request to provided host.
In your case just do
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", url);
response is your HttpServletResponse
object.
Hope this helps.
When a browser receives an HTTP redirect code it will always perform a GET or HEAD to the given url by standard. This is why data must be sent by query strings.
If you want to simulate a redirect by POST, you can send to your client a form with the information you want and, on the page load event, you automatically submit the form using Javascript (commonly used to comunicate between different servers, used by SAML protocol for example). Here's an example:
<form name="myRedirectForm" action="https://processthis.com/process" method="post">
<input name="name" type="hidden" value="xyz" />
<input name="phone" type="hidden" value="9898989898" />
<noscript>
<input type="submit" value="Click here to continue" />
</noscript>
</form>
<script type="text/javascript">
$(document).ready(function() {
document.myRedirectForm.submit();
});
</script>
Side note:
If you already have the information in your server why are you sending a redirect instead of doing the given action?
Maybe you want to implement a POST/REDIRECT/GET pattern?
I do not think this is possible. Why do not you use RequestDispatcher. This will work for you. Just set the parameters in request
request.setAttribute("message", "Hello test");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
OR - The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue.
OR - another option, set the parameters in your session in servlet, if you have session. Then get it from session after you redirect to the required page.