作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我编写了两个驻留在不同 Web 服务器上的 servlet。使用 java 中的 URL 对象从 Servlet1(Server1) 发送请求。并且能够成功调用Servlet2(server2)。但我还需要将响应从 Servlet2 发送回 Servlet1...我怎样才能实现这一点。请帮助我。
更新
这是测试代码......
Servlet1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside MyServlet.");
String urlParameters = "param1=a¶m2=b¶m3=c";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String requestURL = "http://localhost:8080/Application2/Servlet2";
URL url = new URL( requestURL );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "UTF-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
out.write( postData );
conn.connect();
}
Servlet2:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside CallToAuthorize.Getting Access Token.");
//do something here and send the response back to Servlet1.
//Primarily i will be sending String back to Servlet1 for its request.
}
最佳答案
您的 Servlet2(请求接收者)应该正常运行:
一个基本示例:
public class Servlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/plain; charset=UTF-8");
response.getWriter().append("That is my response");
}
}
您的客户端(请求发送者)应该处理响应:
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("SUCCESS");
}
else {
System.out.println("Response Code: " + responseCode);
}
// may be get the headers
Map<String, List<String>> headers = connection.getHeaderFields();
// do something with them
// read the response body (text, html, json,..)
// do something usefull
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
关于java - 如何从另一个 Servlet 将响应发送回 Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999826/
我是一名优秀的程序员,十分优秀!