Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 一个servlet通过http post将字符串传递给另一个servlet_Java_Servlets - Fatal编程技术网

Java 一个servlet通过http post将字符串传递给另一个servlet

Java 一个servlet通过http post将字符串传递给另一个servlet,java,servlets,Java,Servlets,我正在通过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.s

我正在通过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发送的字符串并显示它的正确方法吗?

您可以将字符串作为参数写入发布的servlet中,并在作为参数接收的servlet中读取它

在那篇文章中:

outstr.write(("your_param=" + sb.toString()).getBytes());
接收以下内容的Servlet:

String yourParamValue = request.getParameter("your_param");

试试这个代码,它应该能解决这个问题

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();
    }
定义“这不起作用”。你到底得到了什么?会发生什么?