[英]How to send Response back to Servlet from another Servlet
我已經在不同的Web服務器上編寫了兩個servlet。 使用Java中的URL對象從Servlet1(Server1)發送請求。 並成功調用了Servlet2(server2)。 但是我也需要將響應從Servlet2發送回Servlet1 ...我該如何實現。 請幫我。
UPDATE
這是測試代碼。
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,即Request-Receiver,應正常運行:
一個基本的例子:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.