HttpConection e J2me

5 respostas
L

Ola pessoal,estou iniciando meus esteudos em j2me e estou tentando adaptar o exemplo do livro coreJ2me,criei uma midlet que pega alguns dados e envia para um servelt ,porem nao estou obtendo exito quando eu envio a solicitacao via post ele me abre uma tela no emulador com a seguinte mensagem
{ MobileAplication1 wants to connect to http://localhost:8084/erpMobile/MobileServlets
le using airtime.This may result in charges.

Is it OK use airtime.
}

daew tem os botoes no e yes,so que nao funcionam eu tento comfirmar porem nada acontece parece que ele trava nesta tela,veja meu codigo:

package Mobile.MobileServlets;

import java.io.*;

import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.*;
import javax.servlet.http.*;
import model.ErpOrcamento;

public class OrcamentoMobileServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req,
            HttpServletResponse res)
            throws ServletException, IOException {
         System.out.print("no dopost()");
        doPost(req, res);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
         System.out.print("no dopost()");
        String dataOrcamento = (String) req.getParameter("dataOrcamento");
        String descontoDinheiro = (String) req.getParameter("descontoDinheiro");
        String descontoProcentagem = (String) req.getParameter("descontoPorcentagem");
        String valorProdutos = (String) req.getParameter("valorProdutos");
        String valorServicos = (String) req.getParameter("valorServicos");
        String valorTotal = (String) req.getParameter("valorTotal");
        String clienteId = (String) req.getParameter("clienteId");
        String funcionarioId = (String) req.getParameter("funcionarioId");

        salvar(dataOrcamento, descontoDinheiro, descontoProcentagem, valorProdutos, valorServicos, valorTotal, clienteId, funcionarioId);

        System.out.print("no dopost()");
        res.setContentType("text/plain");
        PrintWriter out = res.getWriter();
        out.close();
    }

    private String salvar(String data, String descDin, String descPorc, String valorProdutos,
            String valorServicos, String valorTotal, String clienteId, String funcionarioId) {

        emf = Persistence.createEntityManagerFactory("erpMobilePU");
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ErpOrcamento orcamento = new ErpOrcamento();
            orcamento.setDataorcamento(new Date(data));
            orcamento.setDescontodinheiro( new BigDecimal(descDin));
            orcamento.setDescontoporcentagem (new BigDecimal(descPorc));
            orcamento.setValorprodutos( new BigDecimal(valorProdutos));
            orcamento.setValorservicos( new BigDecimal(valorServicos) );
            orcamento.setValortotal(new BigDecimal(valorTotal));
            orcamento.setClienteId(new Long(clienteId));
            orcamento.setFuncionarioId( new Long(funcionarioId));
        } catch (Exception e) {
            return e.toString();
        }
        return "ok";
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
}

mildet

package br.com.agile.mobile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

/**
 * @author lgweb
 */
public class OrcamentoViewMobile extends MIDlet implements CommandListener {

    private Display display;
    private DisplayManager displayManager;
    private Form fmMain;
    private Alert alError;
    private Command cmGET;
    private Command cmPOST;
    private Command cmExit;
    private TextField dataOrcamentoField;
    private TextField valorProdutosField;
    private TextField descontoDinheiroField;
    private TextField descontoPorcentagemField;
    private TextField valorServicosField;
    private TextField valorTotalField;
    private TextField clienteIdField;
    private TextField funcionarioIdField;
    private String errorMsg = null;

    public OrcamentoViewMobile() {
        display = Display.getDisplay(this);

        cmGET = new Command("GET", Command.SCREEN, 2);
        cmPOST = new Command("POST", Command.SCREEN, 3);
        cmExit = new Command("Exit", Command.EXIT, 1);

        dataOrcamentoField = new TextField("Data:", "", 8, TextField.ANY);
        valorProdutosField = new TextField("Valor Produtos:", "", 10, TextField.DECIMAL);
        valorServicosField = new TextField("Valor Servicos:", "", 10, TextField.DECIMAL);
        valorTotalField = new TextField("Valor Total:", "", 10, TextField.DECIMAL);
        clienteIdField = new TextField("Cliente:", "", 20, TextField.ANY);
        funcionarioIdField = new TextField("Funcionario:", "", 20, TextField.ANY);
        descontoDinheiroField = new TextField("Desc R$:", "", 10, TextField.DECIMAL);
        descontoPorcentagemField = new TextField("Desc %:", "", 10, TextField.DECIMAL);


        fmMain = new Form("Orcamento");
        fmMain.addCommand(cmExit);
        fmMain.addCommand(cmGET);
        fmMain.addCommand(cmPOST);
        fmMain.append(dataOrcamentoField);
        fmMain.append(valorProdutosField);
        fmMain.append(valorServicosField);
        fmMain.append(valorTotalField);
        fmMain.append(clienteIdField);
        fmMain.append(funcionarioIdField);

        fmMain.setCommandListener(this);
    }

    public void commandAction(Command c, Displayable s) {
        if (c == cmGET || c == cmPOST) {
            try {
                if (c == cmGET) {
                    createOrcamento();
                } else {
                    createOrcamentoPost();
                }
            } catch (Exception e) {
                System.err.println("Msg: " + e.toString());
            }
        } else if (c == cmExit) {
            destroyApp(false);
            notifyDestroyed();
        }
    }

    public void startApp() {
        display.setCurrent(fmMain);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    private void createOrcamento() throws IOException {
        HttpConnection http = null;
        InputStream iStrm = null;

        boolean ret = false;

        String url =
                "http://localhost:8084/erpMobile/MobileServlet" + "?" +
                "dataOrcamento=" + dataOrcamentoField.getString() + "&" +
                "descontoDinheiro=" + descontoDinheiroField.getString() + "&" +
                "descontoPorcentagem=" + descontoPorcentagemField.getString() + "&" +
                "valorProdutos=" + valorProdutosField.getString() + "&" +
                "valorServicos=" + valorServicosField.getString() + "&" +
                "valorTotal=" + valorTotalField.getString() + "&" +
                "clienteId=" + clienteIdField.getString() + "&" +
                "funcionarioId=" + funcionarioIdField.getString();

        try {
            System.out.println("tentando abrir conexao");
            http = (HttpConnection) Connector.open(url);

            http.setRequestMethod(HttpConnection.GET);

            iStrm = http.openInputStream();

            ret = processServerResponse(http, iStrm);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (iStrm != null) {
                iStrm.close();
            }
            if (http != null) {
                http.close();
            }
        }

        if (ret == false) {
            showAlert(errorMsg);
        }
    }

    private void createOrcamentoPost() throws IOException {
        System.out.println("Entrou no servlet");
        HttpConnection http = null;
        OutputStream oStrm = null;
        InputStream iStrm = null;
        boolean ret = false;

        String url =
                "http://localhost:8084/erpMobile/MobileServlet";
        try {
            http = (HttpConnection) Connector.open(url);

            oStrm = http.openOutputStream();

            http.setRequestMethod(HttpConnection.POST);

            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            byte data[] = ("dataOrcamento=" + dataOrcamentoField.getString()).getBytes();
            oStrm.write(data);

            data = ("&descontoDinheiro=" + descontoDinheiroField.getString()).getBytes();
            data = ("&descontoPorcentagem=" + descontoPorcentagemField.getString()).getBytes();
            data = ("&descontoDinheiro=" + descontoDinheiroField.getString()).getBytes();
            data = ("&valorServicos=" + valorServicosField.getString()).getBytes();
            data = ("&valorProdutos=" + valorProdutosField.getString()).getBytes();
            data = ("&valorTotal=" + valorTotalField.getString()).getBytes();
            data = ("&clienteId=" + clienteIdField.getString()).getBytes();
            data = ("&funcionarioId=" + funcionarioIdField.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();
            }

            return true;
        } else {
            errorMsg = new String(http.getResponseMessage());
        }
        return false;
    }

    private void showAlert(String msg) {

        alError = new Alert("Error", msg, null, AlertType.ERROR);

        alError.setTimeout(Alert.FOREVER);

        display.setCurrent(alError, fmMain);
    }
}

Qualquer ajuda e bem vinda Obrigado.
Abracos.

5 Respostas

diogofabri

Esta mensagem de erro diz respeito a Thread…
Tente abrir uma thread ao fazer ao conexão http.
Abraço!

L

cara rodei em uma thread separada e nada,o problema continua se alguem puder ajudar agradeco.
Abracos.

L

alguem tem um outro exemplo ou pode dar uma luz aqui

Y

cara sou novo em j2me, mas dando uma pesquisada sobre este assunto achei este post http://www.guj.com.br/posts/list/130152.java, diferente de vc nosso colega implementa Runnable e executa a conexão dentro de run(), dá uma olhada

S

Cara isso pelo menos é problema de thread sim, quando vc executa e peder permissào de conexao e vc aperta o botão yes, nada acontece pq tu trava a aplicação, faz separado em um thread toda a parte de conexão, ai tu volta a testar, se aparecer o erro, entao revisa sua conexão pois tem algo errado no seu código, mas de cara é obrigatorio uso de thread em uma conexao seja ela por extends thread ou runnable.

Criado 21 de maio de 2009
Ultima resposta 29 de jun. de 2009
Respostas 5
Participantes 4