【问题标题】:How to read my data in servlet from android? [duplicate]如何从android读取我在servlet中的数据? [复制]
【发布时间】:2016-06-16 17:53:39
【问题描述】:

我是处理 servlet 的新手,我试图从 android 应用程序向我的 Servlet 发送数据,但不知道在我的 servlet 中读取数据的确切方法? 在 android 中,我使用这些来发送数据:

            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 中获取它?提前谢谢

【问题讨论】:

  • Google for 'android 从流中读取字符串'。

标签: java android google-app-engine servlets


【解决方案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】:

    这个例子可能对你有所帮助:

     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

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      相关资源
      最近更新 更多