Servlet trava

3 respostas
A
OI, estou fazendo um teste para requisicao de alguns dados usando j2me usando tomcat e servlet e gostarai de saber porque ela esta travando nesta linha
http = (HttpConnection) Connector.open(url);

segue o codigo j2me

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class GetNpost extends MIDlet implements CommandListener
{
    private Display display;
    private Form fmMain;
    Alert alError;
    private Command cmGET;
    private Command cmPOST;
    private Command cmExit;
    private TextField tfAcct;
    private TextField tfPwd;
    private StringItem siBalance;
    private String errorMsg = null;
    
    public GetNpost(){
        display = Display .getDisplay(this);
        
        cmGET = new Command("GET", Command.SCREEN, 2);
        cmPOST = new Command("POST", Command.SCREEN, 3);
        cmExit = new Command("Sair", Command.EXIT, 1);
        
        tfAcct = new TextField("Conta  : ", "", 5, TextField.NUMERIC);
        tfPwd = new TextField("Password: ", "", 10, TextField.ANY | TextField.PASSWORD);
        
        siBalance = new StringItem("Saldo: ", "");
        
        fmMain = new Form("Informações da conta");
        fmMain.addCommand(cmGET);
        fmMain.addCommand(cmPOST);
        fmMain.addCommand(cmExit);
        
        fmMain.append(tfAcct);
        fmMain.append(tfPwd);
        fmMain.append(siBalance);
        
        fmMain.setCommandListener(this);       
    }
    
    public void startApp(){ 
        display.setCurrent(fmMain);
    }
    
    public void pauseApp(){        
    }
    
    public void destroy(boolean unconditional){        
    }
    
    public void commandAction(Command c, Displayable d){
        if (c == cmGET || c == cmPOST){
            try{
                if (c == cmGET)
                    lookupBalance_withGET();
                else
                    lookupBalance_withPOST();
            }catch (Exception e){
                System.out.println("Msg: " + e.toString());
            }
        }else if (c == cmExit){
            //destroyApp(false);
            notifyDestroyed();
        }
    }
    
  private void lookupBalance_withGET() throws IOException{
    HttpConnection http = null;
    InputStream iStrm = null;
    boolean ret = false;
    
    String url = "http://localhost:8080/Servlets/GetNpostServlet" 
            + "?" + 
            "account=" + tfAcct.getString() + "&" +
            "password=" + tfPwd.getString();
    
    try{
      http = (HttpConnection) Connector.open(url);
      http.setRequestMethod(HttpConnection.GET);
      iStrm = http.openInputStream();
      ret = processServerResponse(http, iStrm);
    } 
    finally
    {
        if (iStrm != null)
            iStrm.close();
        if (http != null){
            http.close();
        }
    }
    
    if ( ret = false)
      showAlert(errorMsg);   
  }
  
  private void lookupBalance_withPOST() throws IOException{
    HttpConnection http = null;
    InputStream iStrm = null;
    OutputStream oStrm = null;
    boolean ret = false;
    
    String url = "http://localhost:8080/Servlets/GetNpostServlet";
    try {
      http = (HttpConnection) Connector.open(url);
      oStrm = http.openOutputStream();
      
      http.setRequestMethod(HttpConnection.POST);
      
      http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      
      byte data[] = ("account=" + tfAcct.getString()).getBytes();
      oStrm.write(data);
      
      data = ("&password=" + tfPwd.getString()).getBytes();
      oStrm.write(data);
      oStrm.flush();
      
      iStrm = http.openInputStream();
      
      ret = processServerResponse(http, iStrm);
              
    }
    finally{
      if (iStrm!= null)
          iStrm.close();
      if (oStrm != null)
          oStrm.close();
      if (http != null)
          http.close();
    }
    if (ret == false)
        showAlert(errorMsg);            
  }
  
  private boolean processServerResponse(HttpConnection http, InputStream iStrm) 
          throws IOException{
      errorMsg = null;
      
      if (http.getResponseCode() == HttpConnection.HTTP_OK) {
          int length = (int) http.getLength();
          String str;
          if (length !=-1){
              byte servletData[] = new byte[length];
              iStrm.read(servletData);
              str = new String(servletData);
          }else {
              ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
              int ch;
              while ((ch = iStrm.read()) != -1)
                  bStrm.write(ch);
              
              str = new String(bStrm.toByteArray());
              bStrm.close();
          }
          siBalance.setText(str);
          return true;
      }else
          errorMsg = new String(http.getResponseMessage());
          return false;      
  }
  
  private void showAlert(String msg){
      alError = new Alert("Erro: ", msg, null, AlertType.ERROR);
      
      alError.setTimeout(Alert.FOREVER);
      
      display.setCurrent(alError, fmMain);
  }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

segue o codigo da servlet

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class GetNpostServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    String acct = req.getParameter("account"), 
            pwd = req.getParameter("password");
    
    String balance = accountLookup(acct, pwd);
    
    if (balance == null){
        res.sendError(res.SC_BAD_REQUEST, "Não foi possível localizar a conta!");
        return;
    }
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    out.print(balance);
    out.close();
  }
    
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException { 
    String acct = req.getParameter("acct")  , 
            pwd = req.getParameter("pwd");
    String balance = accountLookup(acct, pwd);
    
    if (balance == null){
        res.sendError(res.SC_BAD_REQUEST, "Não foi possível localizar a conta!");
        return;
    }
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    out.print(balance);
    out.close();    
  }
  
  private String accountLookup(String acct, String pwd){
    Connection con = null;
    Statement st = null;
    StringBuffer msgb = new StringBuffer("");
  
    try {
         Class.forName("com.mysql.jdbc.Driver");
         String Host = "jdbc:mysql://localhost:3306/accinfo";     
         String User = "root";     
         String Password = "2785anma";           
         con = DriverManager.getConnection(Host, User, Password);         
         System.out.println("A conexão foi um sucesso");
         
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT BALANCE FROM ACCTINFO WHERE ACCONT = "
                 + acct + "AND PASSWORD = '" + pwd + "'");
         if (rs.next())
             return rs.getString(1);
         else
             return null;
         
    } catch(ClassNotFoundException e) {
         return e.toString();
     } catch(SQLException e) {
         return e.toString();
     }
  }
  
  public String getServletInfo(){
      return "Tentativa de integracao movel com servidor!";
  }
}

pelo que eu li tem que fazer uma threads porque esta aparecendo a seguinte mensagem "Is it OK to use airtime?", se tiver que fazer como posso fazer?

3 Respostas

malves_info

Ao iniciar Connector.open, vc esta em uma Thread??? se não tente colocar em uma thread a sua conexão.

[]'s

A

malves_info:
Ao iniciar Connector.open, vc esta em uma Thread??? se não tente colocar em uma thread a sua conexão.

[]'s

Oi, nao estou usando nenhuma thread! Voce teria algum tutorial onde ensina a criarm, ou se puder postar algum codigo?

malves_info

Tenho um exemplo meu:

public class RetornaDados implements Runnable{
	private boolean statusThread;
	private String dados;
	public RetornaDados() {}
	
	public String getDados(){
		statusThread = true;
		new Thread(this).start();
		
		while(statusThread){
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				e.getMessage();
			}
		}
		
		return dados; 
	}
	
	public void run(){
		
		HttpConnection httpConn = null;
		InputStream is = null;
		
		try {
 
			 httpConn = (HttpConnection)Connector.open("http://192.0.0.1/fonte/index?variavel=teste");
			 
			 // System.out.println("Conexão Aberta");
			 httpConn.setRequestMethod(HttpConnection.GET);
			 
			 httpConn.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC 1.1");
			 
			// httpConn.setRequestProperty("Connection", "close");
			 
			 is = httpConn.openInputStream();
			 
			 ByteArrayOutputStream baos = new ByteArrayOutputStream();
			 
			 int ch;
			 
			 //ch recebe os bytes
			 while((ch = is.read()) != -1){
				 baos.write(ch);
			 }
			 
			 dados = new String(baos.toByteArray());
			 
			 
		} catch (Exception e) {
			System.out.println("Erro Inespeado: " + e.getMessage());
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(httpConn != null){
				try {
					httpConn.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		statusThread = false;
	}
	
}

Neste Caso estou lendo os dados de um Servidor qualquer, mas vc pode implementar a forma em que a Thread é executada para o Out.

[]'s

Criado 9 de agosto de 2008
Ultima resposta 11 de ago. de 2008
Respostas 3
Participantes 2