我通过http url连接从一个servlet向另一个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发送的字符串并显示它的正确方法吗?
答案 0 :(得分:0)
你可以把你的字符串写成servlet中的参数,在servlet中发布并作为参数接收它。
发布的Servlet:
outstr.write(("your_param=" + sb.toString()).getBytes());
接收的Servlet:
String yourParamValue = request.getParameter("your_param");
答案 1 :(得分:0)
试试这段代码,它应该解决这个问题
try {
BufferedReader reader = request.getReader();
StringBuilder inputStringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
inputStringBuilder.append(line).append("\n");
}
String requestData = inputStringBuilder.toString();
reader.close();
resp.getWriter().write(requestData);
resp.getWriter().flush();
resp.getWriter().close();
} catch (IOException e) {
e.printStacktrace();
}