Servlet接收Android客户端发送的参数为null

时间:2015-08-18 17:36:47

标签: java android servlets

我的问题非常简单。我在Android应用程序中使用HttpURLConnection与服务器通信。 以下是我的Android客户端代码:

public void post() {
        URL url = new URL("http://" + MainActivity.SERVER_IP + "/gov/RegisterServlet");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            Uri.Builder queryBuilder = new Uri.Builder()
                    .appendQueryParameter("token", token)
                    .appendQueryParameter("is_registered", "true");
            String s = queryBuilder.build().getEncodedQuery();

            OutputStreamWriter stream = new OutputStreamWriter(connection.getOutputStream());
            stream.write(s);
            stream.flush();
            stream.close();

            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer responce = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                responce.append(line);
                responce.append('\r');
            }

            Toast.makeText(context, responce.toString(), Toast.LENGTH_LONG).show();
        } finally {
            connection.disconnect();
        }
    }

token是我之前初步化的String。 以下是我的基本Servlet类:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getParameter("token");
        RequestDispatcher d = req.getRequestDispatcher("\\" + token);
        d.forward(req, resp);
    }

但遗憾的是,我在servlet上收到的token始终为null。我的问题是为什么它变为空,并且还有其他更好的解决方案,我想要实现的目标。

谢谢

0 个答案:

没有答案