有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从安卓读取servlet中的数据?

我是处理Servlet的新手,曾试图从安卓应用程序向我的Servlet发送数据,但不知道在我的Servlet中读取数据的确切方式? 在安卓系统中,我使用这些功能发送数据:

            URL url = new URL("http://example.appspot.com/testservlet");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("firstParam", "Rahul")
                    .appendQueryParameter("secondParam", "Anil")
                    .appendQueryParameter("thirdParam", "Rohan");
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();
        }catch(Exception e){
           Exception exep= e;
            Log.d("Test",exep+"");
            return false;
        }
        Log.d("Test","Succesfully")
        return true;

在servlet中,我写道:

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/plain");
            resp.setContentType("text/plain");
               String request=req.getParameter("firstParam");

               resp.getWriter().println("firstParam ::::::::::"+request);
    }

如果不正确,请提供一些示例,例如发送字符串并在servlet中获取它?。先发制人


共 (2) 个答案

  1. # 1 楼答案

    我找到了一个示例,它对您很有用:

    https://github.com/wso2-attic/commons/blob/master/qa/qa-artifacts/app-server/as-5.2.0/myfaces/javaee7/servlet/non-blocking-io-read-war/src/main/java/org/glassfish/servlet/non_blocking_io_read_war/ClientTest.java#L93

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
    
        PrintWriter out = response.getWriter();
    
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Non-blocking-read-war</title>");
        out.println("</head>");
        out.println("<body>");
    
        String urlPath = "http://"
                + request.getServerName()
                + ":" + request.getLocalPort() //default http port is 8080
                + request.getContextPath()
                + "/ServerTest";
    
        URL url = new URL(urlPath);
    
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(2);
        conn.setRequestProperty("Content-Type", "text/plain");
        conn.connect();
    
        try {
            output = conn.getOutputStream();
            // Sending the first part of data to server
            String firstPart = "Hello";
            out.println("Sending to server: " + firstPart + "</br>");
            out.flush();
            writeData(output, firstPart);
    
            Thread.sleep(2000);
    
            // Sending the second part of data to server
            String secondPart = "World";
            out.println("Sending to server: " + secondPart + "</br></br>");
            out.flush();
            writeData(output, secondPart);
    
            // Getting the echo data from server
            input = conn.getInputStream();
            printEchoData(out, input);
    
            out.println("Please check server log for detail");
            out.flush();
        } catch (IOException ioException) {
            Logger.getLogger(ReadListenerImpl.class.getName()).log(Level.SEVERE,
                    "Please check the connection or url path", ioException);
        } catch (InterruptedException interruptedException) {
            Logger.getLogger(ReadListenerImpl.class.getName()).log(Level.SEVERE,
                    "Thread sleeping error", interruptedException);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (Exception ex) {
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (Exception ex) {
                }
            }
        }
    
        out.println("</body>");
        out.println("</html>");
    
    }
    
  2. # 2 楼答案

    此示例可能会帮助您:

     private Document sendRequest(String requestXML) throws Exception {
    
        /**
        // Open HTTP connection with TransitServlet
        URLConnection tc = null;
        try {
            tc = servletURL.openConnection();
        } catch (IOException ioe) {
            throw(ioe);
        }
        tc.setDoOutput(true);
        tc.setDoInput(true);
    
        // Write request to HTTP request body
        OutputStreamWriter out = new OutputStreamWriter(tc.getOutputStream());
        out.write(requestXML);
        out.flush();
        */
        // Read response into XML document object
        DocumentBuilderFactory docBuilderFactory =
            DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        Document xmlDoc = null;
    
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw(pce);
        }
    
        initializeDataField();
    
        InputStream tcIn = null;
        try {
            tcIn = submitRequest(requestXML);
            xmlDoc = docBuilder.parse(tcIn);
        } catch (IOException ioe) {
            throw(ioe);
        } catch (SAXException saxe) {
            throw(saxe);
        }
        //out.close();
        tcIn.close();
    
        // Return XML document object for interpretation
        return(xmlDoc);
    
    }
    

    此处的完整代码:http://code.openhub.net/file?fid=_qOpR4E6jYE2oD88aATVKqO3tP0&cid=jd-01_BUDSM&s=How%20to%20read%20my%20data%20in%20servlet%20from%20android%3F&pp=0&fl=Java&ff=1&filterChecked=true&fp=306406&mp,=1&ml=1&me=1&md=1&projSelected=true#L75