B4J Question send data from b4j app to servlet

Roberto P.

Well-Known Member
Licensed User
Longtime User
from an app created with B4J, I have to send a json text to a tomcat servlet, but the stream seems not to receive the data.
someone can tell me where I'm wrong.

Here is the code.

B4J
B4J:
Dim aHttp As HttpJob
    aHttp.Initialize("send_data2", Me)
    
    aHttp.PostString("http://localhost:8080/hello/servlets/servlet/HelloWorld?username=roberto&password=mypassword", GetJSon)
        
    Wait For (aHttp) JobDone(j As HttpJob)
    
    If j.Success Then
        
        LogError("chiamata avvenuta con successo x invio bytes")
        LogError("ritorno server: ")
        Log(j.GetString)
        
                
        j.Release
        
    Else
        LogError("Chiamata servelet fallita SendObject")
    End If

Servlet trials

servlet:
 //---------------------------------------------------------------------------------------------------------------
     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          
            super.doPost(request, response);
            
             Date date         = new Date();
             PrintWriter out = response.getWriter();
             out.println("risposta del server con DoPost....del " + date.toString() + " " + date.getTime() );
             log("risposta del server con DoPost....del " + date.toString() + " " + date.getTime() );
            
            // this.ReadParameters(request);
            
             String username = request.getParameter("username");
             String password = request.getParameter("password");
            
             out.println("username " + username + " " + "password = " + password);
             log("username " + username + " " + "password = " + password);
                              

             int nRead2                = request.getContentLength();
             log( " lenght content = " + nRead2);
             log("type content = " + request.getContentType());
             log("getContextPath " + request.getContextPath());
            
             BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            
             ServletInputStream sis = request.getInputStream();
            
             log("To string input stream: " + sis.toString());
            
             int nAvailable = sis.available();
             log("Number available: " + nAvailable);
            
             int nRead = sis.read();
             log("Numero di caratteri in canna: " + nRead);
            
             byte[] bt = new byte[1024];
             sis.read(bt);
             log("Lunghezza read byte: " + bt.length);
            
             char[] buffer = new char['?'];
              StringBuilder sb = new StringBuilder(1024);
              int count;
              
              while ((count = rd.read(buffer, 0, buffer.length)) != -1)
              {
              //  int count;
                if (count < buffer.length) {
                  sb.append(new String(buffer, 0, count));
                } else {
                  sb.append(buffer);
                }
              }
            
              log("dati letti " + sb.toString());
              
            
     }

logs
29-Dec-2019 15:03:24.803 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: risposta del server con DoPost....del Sun Dec 29 15:03:24 CET 2019 1577628204803
29-Dec-2019 15:03:24.803 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: username roberto password = mypassword
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: lenght content = 62
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: type content = application/x-www-form-urlencoded
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: getContextPath /hello
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: To string input stream org.apache.catalina.connector.CoyoteInputStream@3d57bc23
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: Number available 0
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: Numero di caratteri in canna -1
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: Lunghezza read byte 1024
29-Dec-2019 15:03:24.804 INFORMAZIONI [http-nio-8080-exec-6] org.apache.catalina.core.ApplicationContext.log HelloWorld: dati letti

Thanks in advance
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
Erel,
thanks for your advice.
but it still doesn't work. Now I see that there are characters in the stream but I can't see them.

B4J:
aHttp.PostString("http://localhost:8080/hello/servlets/servlet/HelloWorld?username=roberto&password=mypassword", GetJSon)
aHttp.GetRequest.SetContentType("application/json" )

I also added the following piece of code in the servlet

servlet:
  String line = rd.readLine();
                 String message = new String();
              
                 while (line  != null) {
                     log("Leggo la linea del file.....");
                     rd.readLine();
                     message += line;
                 }
                
                 log("dati letti 2" + message);




ResponseError. Reason: , Response: <!doctype html><html lang="en"><head><title>HTTP Status 405 ? Method Not Allowed</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 405 ? Method Not Allowed</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> HTTP method POST is not supported by this URL</p><p><b>Description</b> The method received in the request-line is known by the origin server but not supported by the target resource.</p><hr class="line" /><h3>Apache Tomcat/9.0.30</h3></body></html>

do you have any idea?
thank
 
Upvote 0

Roberto P.

Well-Known Member
Licensed User
Longtime User
I've also tried using your TextReaderWrapper class, but throw an exception

B4J:
            TextReaderWrapper aReadeb4j = new TextReaderWrapper();
                aReadeb4j.Initialize(request.getInputStream());
                
                String aData = aReadeb4j.ReadAll();
                aReadeb4j.ReadLine();
                boolean aReady = aReadeb4j.Ready();

29-Dec-2019 18:16:13.215 GRAVE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ServletSynchro] in context with path [/Agon61] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: anywheresoftware.b4a.objects.streams.File$TextReaderWrapper
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1365)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1188)
at ServletSynchro.doPost(ServletSynchro.java:230)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at SPServlet.service(spservlet.java:4045)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

why?
 
Upvote 0

Roberto P.

Well-Known Member
Licensed User
Longtime User
SOLVED

B4J:
    aHttp.PostString("http://localhost:8080/Agon61/servlets/servlet/ServletSynchro?username=roberto&password=sitranica", GetJSon) '
    
    aHttp.GetRequest.SetContentEncoding("UTF-8")
    aHttp.GetRequest.SetContentType("application/text" )

servlet:
final StringBuilder builder = new StringBuilder();
                BufferedReader reader = request.getReader();
                
                 if (reader == null) {
                       log("Request body could not be read because it's empty.");
                    }
                    
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    
                    log("Dati dal Client: " + builder.toString());


THANK EREL
 
Upvote 0
Top