How to redirect a POST request from a servlet to another application
Can we redirect a开发者_C百科 POST request from a servlet in one application deployed in server1 to an endpoint in another application deployed in server2? Is this possible with POST request without loss of data or does it always need to be a GET request?
Several ways:
If your current request is already a POST request, just explicitly send a 307 redirect instead of a 302 redirect (the
response.sendRedirect()
sets by default a status code of 302).response.setStatus(307); response.setHeader("Location", "https://other.com");
This will however issue a security confirmation warning at the client side in some web browsers.
Play for proxy yourself.
URLConnection connection = new URL("https://other.com").openConnection(); connection.setDoOutput(true); // POST // Copy headers if necessary. InputStream input1 = request.getInputStream(); OutputStream output1 = connection.getOutputStream(); // Copy request body from input1 to output1. InputStream input2 = connection.getInputStream(); OutputStream output2 = response.getOutputStream(); // Copy response body from input2 to output2.
This will however not change the URL and the client thinks he's still on your site. See also How to use java.net.URLConnection to fire and handle HTTP requests for more detail on how to use
URLConnection
.Convert all POST data to a query string suitable for a GET request so that a 302 redirect can be used nonetheless.
String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = StandardCharsets.UTF_8.name(); request.setCharacterEncoding(encoding); } StringBuilder query = new StringBuilder(); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { for (String value : entry.getValue()) { if (query.length() > 0) { query.append("&"); } query.append(URLEncoder.encode(entry.getKey(), encoding)); query.append("="); query.append(URLEncoder.encode(value, encoding)); } } response.sendRedirect("https://other.com?" + query);
Yes you can using HTTPURLConnection
here is example
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
//log it ,sms it, mail it
}
精彩评论