gpt4 book ai didi

java - 如何从另一个 Servlet 将响应发送回 Servlet

转载 作者:行者123 更新时间:2023-11-30 02:43:18 25 4
gpt4 key购买 nike

我编写了两个驻留在不同 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&param2=b&param3=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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com