Duvida POST

Galera é o seguinte estou montando um midlet que acessa um servlet, ele funciona corretamente, o problema surge no momento em que mudo a forma de transmissão de GET para POST, segue abaixo os codigos.

MIDLET

Método utilizado GET “FUNCIONA CORRETAMENTE”

private void verifica_Login() throws IOException { String url = "http://localhost:8084/RKAM_ServLet/ServLet?"; url = url + "login=" + loginScreen.getUsername() + "&senha=" + loginScreen.getPassword() + "&metodo=LOGIN"; //String url = "http://localhost:8084/RKAM_ServLet/ServLet"; HttpConnection http = null; //OutputStream out = http.openOutputStream();//enviar dados InputStream in = null; try { http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET); /*http.setRequestMethod(HttpConnection.POST); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //http.setRequestProperty("Conexão", "close"); String teste; byte dados[] = ("login=" + loginScreen.getUsername()).getBytes(); teste=new String(dados); out.write(dados); dados = ("&senha=" + loginScreen.getPassword()).getBytes(); teste=teste+new String(dados); out.write(dados); dados = ("&metodo=LOGIN").getBytes(); teste=teste+new String(dados); out.write(dados); out.flush();*/ //--------------TRATAR RESPOSTA DO SERVLET---------------------- in =http.openInputStream();//pegar resposta if (http.getResponseCode() == HttpConnection.HTTP_OK) { int length = (int) http.getLength(); String str; if (length != -1) {//tamanho da resposta conhecido byte data[] = new byte[length]; in.read(data); str = new String(data); } else {//tamanho não conhecido, deve ser pegar bit por bit até chegar ao final ByteArrayOutputStream aux = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) != -1) { aux.write(ch); } str = new String(aux.toByteArray()); aux.close(); } if (str.equals("TRUE")) { set_boo(true); } else { set_boo(false); } } else { System.out.println(http.getResponseMessage()); } in.close(); http.close(); } catch (IOException e) { } }

Método utilizado POST “C/ PROBLEMAS”

private void verifica_Login() throws IOException { //String url = "http://localhost:8084/RKAM_ServLet/ServLet?"; //url = url + "login=" + loginScreen.getUsername() + "&senha=" + loginScreen.getPassword() + "&metodo=LOGIN"; String url = "http://localhost:8084/RKAM_ServLet/ServLet"; HttpConnection http = null; InputStream in = null; try { http = (HttpConnection) Connector.open(url); // http.setRequestMethod(HttpConnection.GET); http.setRequestMethod(HttpConnection.POST); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //http.setRequestProperty("Conexão", "close"); OutputStream out = http.openOutputStream();//enviar dados String teste; byte dados[] = ("login=" + loginScreen.getUsername()).getBytes(); teste=new String(dados); out.write(dados); dados = ("&senha=" + loginScreen.getPassword()).getBytes(); teste=teste+new String(dados); out.write(dados); dados = ("&metodo=LOGIN").getBytes(); teste=teste+new String(dados); out.write(dados); out.flush(); //--------------TRATAR RESPOSTA DO SERVLET---------------------- in =http.openInputStream();//pegar resposta if (http.getResponseCode() == HttpConnection.HTTP_OK) { int length = (int) http.getLength(); String str; if (length != -1) {//tamanho da resposta conhecido byte data[] = new byte[length]; in.read(data); str = new String(data); } else {//tamanho não conhecido, deve ser pegar bit por bit até chegar ao final ByteArrayOutputStream aux = new ByteArrayOutputStream(); int ch; while ((ch = in.read()) != -1) { aux.write(ch); } str = new String(aux.toByteArray()); aux.close(); } if (str.equals("TRUE")) { set_boo(true); } else { set_boo(false); } } else { System.out.println(http.getResponseMessage()); } in.close(); http.close(); } catch (IOException e) { } }

SERVLET

[code]public class ServLet extends HttpServlet {

private Connection c;
String metodo;


public void init() {
  conectar();
}

public void destroy() {
  desconectar();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    metodo = request.getParameter("metodo").toUpperCase();
    if (metodo.equals("LOGIN"))//login
    {
        login(request, response);
    }

    if (metodo.equals("CONSULTA")) {
        consulta(request, response);
    }

}

private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String senha = request.getParameter("senha").toUpperCase();
        String login = request.getParameter("login").toUpperCase();
        //conectar();
        ResultSet res = consultar("select * from login where login='" + login + "' and senha='" + senha + "'");
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        boolean aux = true;
        while (res.next()) {
            out.print("TRUE");
            aux = false;
        }
        if (aux) {
            out.print("FALSE");
        }
        out.close();
        //desconectar();
    } catch (SQLException ex) {
        Logger.getLogger(ServLet.class.getName()).log(Level.SEVERE, null, ex);
    }
}[/code]

O erro ocorre na linha 22 do SERVLET, no momento em que a variavel metodo na servlet recebe o parametro “metodo” passado, caso ele for passado por GET esta variavel recebe o parametro sem problemas, mas se foi passado pelo metodo POST, no momento que a variavel recebe o parametro a servlet fecha e exibe uma mensagem de erro “Internal servlet error”, assim nada é retornado para a midlet, creio que o problema esta na passagem dos dados pelo modo POST pela midlet caso seja isso como resolver?

Quando executo a servlet na saida tenho as seguintes mensagens

Using CATALINA_BASE:   C:\Documents and Settings\Administrador\.netbeans\6.0\apache-tomcat-6.0.14_base
Using CATALINA_HOME:   C:\Arquivos de programas\Apache Software Foundation\Apache Tomcat 6.0.14
Using CATALINA_TMPDIR: C:\Documents and Settings\Administrador\.netbeans\6.0\apache-tomcat-6.0.14_base\temp
Using JRE_HOME:        C:\Arquivos de programas\Java\jdk1.6.0_02
Listening for transport dt_shmem at address: tomcat_shared_memory_id
19/03/2008 17:50:41 org.apache.catalina.core.AprLifecycleListener init
INFO: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Arquivos de programas\Java\jdk1.6.0_02\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\oraclexe\app\oracle\product\10.2.0\server\bin;C:\ARQUIV~1\Borland\Delphi5\Projects\Bpl;C:\ARQUIV~1\Borland\vbroker\jre\Bin;C:\ARQUIV~1\Borland\vbroker\Bin;C:\ARQUIV~1\Borland\Delphi5\Bin;C:\ARQUIV~1\Borland\CBUILD~1\Projects\Bpl;C:\ARQUIV~1\Borland\CBUILD~1\Bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;c:\Arquivos de programas\Microsoft SQL Server\90\Tools\binn\;C:\Arquivos de programas\SSH Communications Security\SSH Secure Shell;C:\Arquivos de programas\Arquivos comuns\Ahead\Lib\
19/03/2008 17:50:41 org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8084
19/03/2008 17:50:41 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 653 ms
19/03/2008 17:50:41 org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
19/03/2008 17:50:41 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.14
19/03/2008 17:50:42 com.sun.faces.config.ConfigureListener contextInitialized
INFO: Initializing Sun's JavaServer Faces implementation (1.2_04-b10-p01) for context '/JJLocadora6'
19/03/2008 17:50:43 org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base C:\Documents and Settings\Administrador\Meus documentos\NetBeansProjects\teste\build\web does not exist or is not a readable directory
        at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:141)
        at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:3944)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4113)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
        at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
        at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
        at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
        at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
        at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
        at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
        at org.apache.catalina.core.StandardService.start(StandardService.java:516)
        at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
19/03/2008 17:50:43 org.apache.catalina.core.StandardContext start
SEVERE: Error in resourceStart()
19/03/2008 17:50:43 org.apache.catalina.core.StandardContext start
SEVERE: Error getConfigured
19/03/2008 17:50:43 org.apache.catalina.core.StandardContext start
SEVERE: Context [/teste] startup failed due to previous errors
19/03/2008 17:50:43 org.apache.catalina.core.StandardContext stop
INFO: Container org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/teste] has not been started
19/03/2008 17:50:43 org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8084
19/03/2008 17:50:43 org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
19/03/2008 17:50:43 org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/31  config=null
19/03/2008 17:50:43 org.apache.catalina.startup.Catalina start
INFO: Server startup in 2279 ms

Alguem pode me confirma o código e me dar uma dica? Obrigado!!!

Cara, nao tenho certeza mas faz um teste ai. Coloca essa linha do seu codigo que faz o post na midlet:
OutputStream out = http.openOutputStream();//enviar dados , apos a linha 12, onde vc ja conectou na URL e ja setou as propriedades do header.

[]'s

ha foi mal aquilo ali eu copiei errado, ele estava abaixo da conexão sim, e da o mesmo erro.

adicionei as respostas dadas pelo tomcat na inicialização da servlet, aparece aqueles erros acima, mas estranho que se eu colocar o get tudo funciona normalmente, o problema esta em usar o post.

Ok, vamos tentar outra então. Poe isso entre a linha 15 e 16:

http.setRequestProperty(“Content-Length”, Integer.valueOf(dados.length));

Eu vi num artigo sobre http o seguinte:

Content-Length: This header is necessary as well, as it specifies the length of the body. By giving this header, you are ensuring that the server WILL read all the data that you?ve sent in the body.

Talvez o servlet nao esteja pegando o body do seu post pq esse header nao foi setado. Tenta aí.

[]'s

[quote=wchevreuil]Ok, vamos tentar outra então. Poe isso entre a linha 15 e 16:

http.setRequestProperty(“Content-Length”, Integer.valueOf(dados.length));

Eu vi num artigo sobre http o seguinte:

Content-Length: This header is necessary as well, as it specifies the length of the body. By giving this header, you are ensuring that the server WILL read all the data that you?ve sent in the body.

Talvez o servlet nao esteja pegando o body do seu post pq esse header nao foi setado. Tenta aí.

[]'s

[/quote]

infelizmente não resolveu, coloquei em baixo da linha 15 e 16, coloquei em baixo da ultima linha quando passa o os valores para a o parametro metodo, e tb tentei colocar em todas as linhas abaixo das que o dados recebe valores, e não deu certo, e os parametros para o setRequestProperty é de (String,String) ai converti o integer voltado pelo dados.length para string.
Mas de nada adiantou :frowning: fods!!!

Desculpe (talvez pela ignorância) mas seu erro é com o diretório onde a aplicação foi construída. Acho que você deveria recompilar seu projeto e ver se vc tem permissão de acesso aos arquivos. Talvez trocar de diretório. Só estou izendo isso pq foi a excessão que foi gerada.

Tenta primeiro setar a sua variavel dados inteira, pra so depois chamar o “out.write()”, isso pq eu acho que depois que vc abre o outputstream nao tem como setar header mais. Assim, testa substituir o seu codigo da linha 8 a 24 pelo codigo abaixo:

http = (HttpConnection) Connector.open(url);

// http.setRequestMethod(HttpConnection.GET);

http.setRequestMethod(HttpConnection.POST);

http.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);

           String conteudo = "login=" + loginScreen.getUsername() + 
                          "&senha=" + loginScreen.getPassword() + "&metodo=LOGIN";

            http.setRequestProperty("Content-Length", (new Integer(conteudo.length())).toString());

//http.setRequestProperty(“Conexão”, “close”);

OutputStream out = http.openOutputStream();//enviar dados

out.write(conteudo.getBytes());

out.flush();

[quote=wchevreuil]Tenta primeiro setar a sua variavel dados inteira, pra so depois chamar o “out.write()”, isso pq eu acho que depois que vc abre o outputstream nao tem como setar header mais. Assim, testa substituir o seu codigo da linha 8 a 24 pelo codigo abaixo:

http = (HttpConnection) Connector.open(url);

// http.setRequestMethod(HttpConnection.GET);

http.setRequestMethod(HttpConnection.POST);

http.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);

           String conteudo = "login=" + loginScreen.getUsername() + 
                          "&senha=" + loginScreen.getPassword() + "&metodo=LOGIN";

            http.setRequestProperty("Content-Length", (new Integer(conteudo.length())).toString());

//http.setRequestProperty(“Conexão”, “close”);

OutputStream out = http.openOutputStream();//enviar dados

out.write(conteudo.getBytes());

out.flush();

[/quote]

é amigo tb não deu certo