【发布时间】:2017-04-21 08:32:00
【问题描述】:
我编写了两个驻留在不同 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.
}
【问题讨论】:
-
它与寻呼机重定向有何不同?
-
现在很清楚问题出在哪里。一些代码总是有助于更好地理解。