POST调用另一台服务器 [英] POST call to another server
问题描述
HI,
我们可以从一台服务器到另一台Web服务器进行POST调用。例如,在server1中部署了一个Web应用程序。当我们调用server2中部署的Web应用程序时,我们可以使用POST方法类型调用。或者它总是可以是带有显式网址的GET方法
Can we make the POST call from one server to another web server. For example, one web application deployed in server1. When we call the web application deployed in the server2, can we call using the POST method type. or always it can be GET method with explicit URLs
推荐答案
两种方式:
-
如果您当前的请求已经是POST,请发送307重定向。
If your current request is already POST, just send a 307 redirect.
response.setStatus(307);
response.setHeader("Location", "http://other.com");
但是,这会在客户端发出安全确认警告。
This will however issue a security confirmation warning at the client side.
自己玩代理。
URLConnection connection = new URL("http://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.
但这不会改变URL,客户认为他仍然在你的网站上。
This will however not change the URL and the client thinks he's still on your site.
参见:
- 如何使用URLConnection来触发和处理HTTP请求?
- How to use URLConnection to fire and handle HTTP requests?
See also:
更新:你其实想要从POST重定向到GET,包括所有请求参数。在这种情况下,只需收集POST参数并将它们作为查询字符串一起发送到默认(302)重定向。
Update: you actually wanted to redirect from POST to GET including all request parameters. In this case, just collect the POST parameters and send them along as query string in a default (302) redirect.
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
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("http://example.com?" + query);
这篇关于POST调用另一台服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!