0

I am new in handling servlets and was trying to send data to my Servlet from android app,but dont know the exact way to read it in my servlet? In android i have used these to send data:

            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;

After in servlet i wrote as:

@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);
    }

Is this correct if not please provide me some examples like sending a string and getting it in servlet?. Thanx in advance

Rahul Verma
  • 404
  • 1
  • 5
  • 15

2 Answers2

-1

This example might help you:

 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);

}

Full code here: 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

unilux
  • 21
  • 1
-2

I found an example and it can be useful for you:

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>");

}
Dongsun
  • 124
  • 2