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

时间:2016-12-06 16:09:53

标签: java servlets

我写了两个驻留在不同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.
 }

1 个答案:

答案 0 :(得分:2)

您的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);
}