Conexão http

6 respostas
M

Pessoal,

Gostaria de saber se existe alguma forma de fazer uma conexão http apartir de uma aplicação desktop? Ou é necessário a criação de um modulo web para essa conexão?

6 Respostas

davidbuzatto

Tem sim.
É só criar uma URLConnection a partir de uma URL.
Dê uma olhada no método openConnection da classe URL.

[]´s

Alexandre_Saudate

Dê uma conferida no Apache Commons HTTP.

[]´s

dooda

Não sei qual é sua ideia com esta conexão, mas abri um tópico resolvido que pode te dar uma ideia

de como abrir a conexão e chamar um webService, inclusive transferindo objetos sem parser…

segue: http://www.guj.com.br/posts/list/203210.java

Att.

M

dooda,

a aplicação que você fez utiliza acessa web, a aplicação que vou fazer vai rodar na rede interna, é por isso que estou querendo ver a possibilidade de criar um cliente - servidor desktop mesmo.

eu fiz um teste só que esta dando um erro:

vou postar o cliente e o servidor espero que vocês possam me ajudar.

Código do Server:

public static final Integer NUM_PORTA = 2002;
    public static final String HOST = "10.144.8.57";

    public static void main(String[] args) throws Exception {
        HTTPSServerExample hTTPSServer = new HTTPSServerExample();
        SSLContext sslContext = hTTPSServer.createSSLContext();
        SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
        SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(NUM_PORTA);

        // client authenticate where possible
        sSock.setWantClientAuth(true);

        for (;;) {
            SSLSocket sslSock = (SSLSocket) sSock.accept();

            try {
                sslSock.startHandshake();
            } catch (IOException e) {
                continue;

            }

            hTTPSServer.readRequest(sslSock.getInputStream());

            SSLSession session = sslSock.getSession();

            try {
                Principal clientID = session.getPeerPrincipal();

                System.out.println("client identified as: " + clientID);
            } catch (SSLPeerUnverifiedException e) {
                System.out.println("client not authenticated");
            }

            hTTPSServer.sendResponse(sslSock.getOutputStream());

            sslSock.close();
        }
    }

Código do Client:

public static final Integer NUM_PORTA = 2002;
    public static final String HOST = "10.144.8.57";

    public static void main(String[] args) throws Exception {
        HTTPSClientExample hTTPSClient = new HTTPSClientExample();
        SSLContext sslContext = hTTPSClient.createSSLContext();
        SSLSocketFactory fact = sslContext.getSocketFactory();

        // specify the URL and connection attributes
        URL url = new URL("https://" + HOST + ":" + NUM_PORTA);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        connection.setSSLSocketFactory(fact);

        connection.setHostnameVerifier(new Conexao.Validator());
        connection.connect();

        // read the response
        InputStream in = connection.getInputStream();

        int ch = 0;
        while ((ch = in.read()) >= 0) {
            System.out.print((char) ch);
        }
    }

O servidor funciona normalmente, porém o erro ocorre quando eu tento inicar o cliente.
Erro:

Exception in thread "main" java.io.IOException: HTTPS hostname wrong:  should be <10.144.8.57>
        at sun.net.www.protocol.https.HttpsClient.checkURLSpoofing(HttpsClient.java:524)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:448)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:133)
        at Conexao.IniciarConexao.main(IniciarConexao.java:34)
Java Result: 1
dooda

não tenho muita noção disso ai que vc fez não mas…

não sei se tem fundamento, mas tentou usar sem o HTTPS ?

Att.

M

Tentei não. mas foi solicitado https, não posso utilizar outro tipo de conexão.
Vou tentando aqui…se alguém souber alguma coisa e possa me ajudar…agradeço!
Aos que tentaram …muito obrigado!

Criado 1 de junho de 2010
Ultima resposta 1 de jun. de 2010
Respostas 6
Participantes 4