我正在通过 http url 连接将字符串从一个 servlet 发送到另一个:
final HttpURLConnection http = (HttpURLConnection) url.openConnection(); // here url is the url of the second servlet
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setDoInput(true);
http.setUseCaches(false);
final OutputStream outstr = http.getOutputStream();
outstr.write(sb.toString().getBytes());
outstr.flush();
outstr.close();
我面临的问题是将其作为来自另一个 servlet 的请求来阅读。我尝试在第二个 servlet 的 getPost 方法中编写以下代码,但这不起作用:
try {
int len = req.getContentLength();
byte[] input = new byte[len];
ServletInputStream sin = req.getInputStream();
int c, count = 0;
while ((c = sin.read(input, count, input.length - count)) != -1) {
count += c;
}
sin.close();
String inString = new String(input);
String decodedString = URLDecoder.decode(inString, "UTF-8");
log.info("Response received - ");
log.info(decodedString);
resp.getWriter().write(decodedString);
resp.getWriter().flush();
resp.getWriter().close();
} catch (IOException e) {
}
有人可以帮助获取第一个 servlet 发送的字符串并显示它的正确方法是什么?