Ir ao conteúdo

Cliente e Servidor, Java XML-RPC

Boa noite,

Como havia comentado a algum tempo atrás, estava trabalhando com um cliente XML-RPC em Java, durante a fase de desenvolvimento do mesmo tive que criar um servidor XML-RPC hipotetico para testar as funcionalidades do cliente, enquanto o servidor certo ainda não estava disponivel para minha pessoa.

Resumidamente para você que não conhece XML-RPC ele é um “formato” , um “jeito”, não sei ao certo a palavra certa para definir agora, onde você cria um servidor e o mesmo quando requisitado faz as operações necessarias e retorna um resultado. Um exemplo seria, você tem um código de criptografia que funciona MUITO bem em C, mas seu sistema é todo em Java, você poderia criar um Cliente JAVA e um Servidor C onde o Java faria requisição para Criptografar as coisas. Talvez utilizar XML-RPC de Java para Java possa ser meio estranho, mas quando os serviços estão distantes, pode ser algo util.

Para começar a mexer com o XML-RPC no Java eu utilizei o apache xml-rpc. Após isso apenas desenvolvi.

Baixe os exemplos cliente e servidor xml-rpc em java.

Servidor:

package xmlrpc;

import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.webserver.WebServer;

public class ServidorXMLRPCParaTestes {

private static ServidorXMLRPCParaTestes euMesmo = null;

private ServidorXMLRPCParaTestes() {
try {
WebServer server = new WebServer(8185); // Cria um servidor na porta 8185
XmlRpcServer servidor = server.getXmlRpcServer(); // Pega o servidor XmlRpc
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.addHandler(“Calc”, Calculadora.class); // Adiciona um novo “handler” ao PHM
servidor.setHandlerMapping(phm); // Define o handler no servidor
server.start(); // inicia o servidor.
} catch (Exception exception) {
System.err.println(“JavaServer: ” + exception);
}
}

public static ServidorXMLRPCParaTestes obterInstância() {
if (euMesmo == null)
euMesmo = new ServidorXMLRPCParaTestes();
return euMesmo;
}
}

– Eu utilizeo o obterInstancia para não poder existir mais de um ServidorXMLRPC 😉
– O handler faz o seguinte, quando for chamado Calc.METODO no servidor ele irá buscar dentro do Calculadora.class

Handler Calculadora:

package xmlrpc;

public class Calculadora {

public int soma(int x, int y) {
return x + y;
}
public int subtracao(int x, int y) {
return x – y;
}

}

Cliente XML-RPC generico:

package xmlrpc;

import java.net.URL;
import org.apache.xmlrpc.*;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public class ClienteXmlRpc {

private static final String urlServidor = “http://localhost:8185”; //DEFINE A URL DO SERVIDOR
private XmlRpcClient xmlrpc;

public ClienteXmlRpc() {
try {
XmlRpcClientConfigImpl configuraçãoCliente = new XmlRpcClientConfigImpl();
configuraçãoCliente.setServerURL(new URL(urlServidor));

xmlrpc = new XmlRpcClient();
xmlrpc.setConfig(configuraçãoCliente);

} catch (Exception exception) {
exception.printStackTrace();
}
}

public Object executar(String comando, Object[] parametros) {
try {
Object resposta = xmlrpc.execute(comando, parametros);
return resposta;
} catch (XmlRpcException e) {
e.printStackTrace();
return null;
}
}

}

– Acredito que o Cliente XML-RPC e o Cliente são auto-explicativos. Qualquer duvida entre em contato.

CalculadoraCliente:

package cliente;

import xmlrpc.ClienteXmlRpc;

public class CalculadoraCliente {
private ClienteXmlRpc cliente;

public CalculadoraCliente() {
cliente = new ClienteXmlRpc();
}

public int soma(int x, int y) {
Object[] parametros = new Object[]{new Integer(x), new Integer(y)};
Integer resultado = (Integer) cliente.executar(“Calc.soma”, parametros);
return resultado;
}

public int subtracao(int x, int y) {
Object[] parametros = new Object[]{new Integer(x), new Integer(y)};
Integer resultado = (Integer) cliente.executar(“Calc.subtracao”, parametros);
return resultado;
}
}

Para rodar os mesmos e testar gerei 2 classes com main e executei as mesmas (executando primeiro o servidor é claro)

RodarServidor:

import xmlrpc.ServidorXMLRPCParaTestes;

public class RodarServidor {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServidorXMLRPCParaTestes Servidor = ServidorXMLRPCParaTestes.obterInstância();
}

}

RequisicaoCliente:

import cliente.CalculadoraCliente;

public class RequisicaoCliente {

/**
* @param args
*/
public static void main(String[] args) {
CalculadoraCliente x = new CalculadoraCliente();
System.out.println(x.soma(1, 1));
}

}

Abraços,
Matheus

Publicado emAprendendojava

15 Comentários

  1. Matheus, valeu pelo post cara, eu procurei por todo canto um exemplo que funcionasse e nenhum funcionava, mas o seu funcionou.

    Agora, eu gostaria de saber se você sabe como fazer pra enviar arquivos usando xml-rpc.

    Abraço

  2. Fernando Fernando

    Cara seu modelo foi fundamental pra mim .. so que fiquei com uma duvuida estou do lado cliente e sei que o lado servidor recebe o seguinte XML

    cti.PEGA_VARIOS_EVENTOS

    DISPOSITIVO
    7144,7377,7147

    SENHA_DISPOSITIVO
    4567

    NUMERO_EVENTO
    100

    e me retorna uma resposta um Vector de varios eventos . Agora minha duvida como passar esse parametros via Apache XML-RPC?

    veja como eu estou tentando passar os parametro..

    ClienteXmlRpc cliente = new ClienteXmlRpc();
    Object[] params = new Object[] {“DISPOSITIVO”, new String(“2001,2002,2003″),”SENHA_DISPOSITIVO”,new String(“4567”), “NUMERO_EVENTO”,new String(“0”) };
    Vector resp = (Vector) cliente.executar(“cti.PEGA_VARIOS_EVENTOS”,params);

    Tem como eu passar o XML ou os parametros como funciona isso me da uma luz please????

  3. Fernando Fernando

    “Chamando Método:
    (cti.PEGA_VARIOS_EVENTOS)
    DISPOSITIVO 7144,7377,7147 SENHA_DISPOSITIVO 4567 NUMERO_EVENTO 100

    POST /RPC2 HTTP/1.0

    cti.PEGA_VARIOS_EVENTOS

    DISPOSITIVO
    7144,7377,7147

    SENHA_DISPOSITIVO
    4567

    NUMERO_EVENTO
    100

    </methodCall"

  4. Fernando diz:
    Valeu Matheus .. deu certo brow..

    URL faltava o rpc2 e para a passagem de parametros usei um linkehashmap dentro do object

    LinkedHashMap chaveValor = new LinkedHashMap();
    chaveValor.put(“DISPOSITIVO”, disp);
    chaveValor.put(“SENHA_DISPOSITIVO”, pass);
    chaveValor.put(“NUMERO_EVENTO”,evt);

    Object[] params = new Object[] { chaveValor };

    sua ajuda foi de extrema importância..
    precisando estamos ai também.
    abraço

    (Publicando o e-mail que ele me enviou, com a solucao do problema ja que auxiliei ele por e-mail. Deixo aqui a solucao pra se alguem tiver o mesmo problema.)

  5. Anthony Anthony

    Cara parabéns pelo post…
    Aqui ta dando o seguinte problema
    Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/ws/commons/serialize/DOMSerializer

    Poderia me ajudar?
    Tanto o servidor como o cliente

    Ja fiz algumas pesquisas e adicionei todos os .jar necessários, e mesmo assim, continua.

    Obrigado…

  6. Diese können beispielsweise einen Teil Ihres ersten Live Casino Einsatzes matchen oder
    sogar Cashback für Verluste anbieten. Suchen Sie nach
    Boni, die speziell für Live Dealer Online-Casinospiele entwickelt wurden.
    Online Casinos bieten solche Boni häufig an und geben Ihnen beim
    Spielen von Online-Blackjack, Online-Roulette oder Baccarat ein Sicherheitsnetz.
    Oft kommen diese mit günstigen Umsatzbedingungen und der
    Chance auf hohe Gewinne daher. Casinos wie Winsane und Roby
    sind für ihre mobile Benutzerfreundlichkeit bekannt und bieten häufig maßgeschneiderte Boni für das Spielen von unterwegs an. Das können zum Beispiel exklusive Freispiele für Slots auf Ihrem Smartphone oder Tablet sein.
    Den Willkommensbonus erhältst du nach Aktivierung des Bonus und
    der ersten Einzahlung. Wenn Freispiele nicht auf ein bestimmtes Spiel
    festgesetzt sind, stehen dir diese oft für eine Auswahl an Spielautoamten bereit.
    Nein, oft sind bestimmte Spielekategorien ausgeschlossen und tragen oft gar nicht oder
    nur prozentuell zum Erfüllen der Bonusbedingungen bei. Freispiele, Echtgeld Bonus und Bonus ohne Einzahlungen. Ein klassischer Bestandskundenbonus, bei dem
    eine weitere Einzahlung aufgewertet wird, nennt sich Reload Bonus.
    Avalon ist ebenfalls ein erfahrenes und seriöses Casino mit
    starkem und fairem Willkommensbonus.
    Wenn Du bei Leonbet durchstartest, erwartet dich ein klassischer Einzahlungsbonus.

    ❌ Keine Freispiele für Neukunden ✅ Vertretbare Bonus- und Umsatzbedingungen ✅ Willkommensbonus von bis zu 1.000 Euro ✅ Willkommensbonus von bis zu 2.000
    Euro ✅ Großartiger Willkommensbonus von bis zu 4.000 Euro

    References:
    https://online-spielhallen.de/druckgluck-casino-aktionscodes-dein-schlussel-zu-besseren-spielerlebnissen/

  7. For crypto players seeking the utmost quality across online casino gaming, live dealer options, and sports betting with a dedication to player value, FortuneJack emerges as a premier one-stop shop.
    For these reasons, Vave Casino earns our highest recommendation as a one-stop hub for crypto
    casino gaming and sports betting with the
    features, transparency, and performance to satisfy today’s discerning players.
    Vave Casino is a feature-rich crypto gaming hub with thousands of outstanding slots, tables,
    live dealer, and sports betting options powered by top
    studios and catering to all play styles through generous welcome bonuses and recurring promotions.
    Flush Casino is a premier crypto-focused online casino launched
    in 2021 that has quickly established itself as a top destination for
    players seeking a modern, feature-rich gambling experience.
    Flush Casino is a top-tier crypto-only online casino featuring over 5,
    500 games, lucrative welcome bonuses up to $1,000, and
    instant payouts across 9 popular cryptocurrencies. Players can explore endless slots, classic table games, live dealers and more while taking advantage of generous
    sign-up bonuses, ongoing promos, instant crypto payouts
    and around-the-clock customer support.
    Established in 2014, Bitcasino.io is one of the most popular and
    reputable crypto casino sites around.

    CasinoBet Casino is a modern crypto-focused platform offering
    instant transactions, exclusive crash-style games, and
    a rewarding loyalty system. It offers over 5,000 games including slots, table games, and liv… TrustDice is a reputable
    crypto gambling site that hosts a large, varied range
    of casino games. Cobra Casino is an elite online gambling site,
    which offers a huge welcome bonus and a strong VIP program.

  8. Big candy casino is a vibrant online platform that
    stands out in the Australian iGaming landscape. Whether you’re prowling around for the next no deposit
    bonus 2025 or diving headfirst into high-stakes roulette,
    Big Candy Casino is prepared to treat you to a world of colorful fun. So go ahead—complete your a
    big candy casino login and see if you can spin your way into a sweet windfall.
    Once your account is ready, you can deposit real money or hunt for more free chips and no deposit
    codes.
    Seasonal promotions and exclusive tournament entry codes appear regularly via email
    and on-site notifications, ensuring active players constantly access fresh value.

    Our platform displays current jackpot totals in real-time, letting you track prize growth and select the most lucrative opportunities.

    Games like Fortunate Buddha and Aztec’s Treasure Feature Guarantee have crowned multiple winners with
    five-figure payouts this month alone, as evidenced by our real-time winner feed displaying actual player
    victories.
    A Big Candy Casino is more than just another gaming site — it’s a full-on sensory experience built with Aussie players in mind.
    Whether you need help with account verification, deposits, withdrawals, or bonuses, our professional
    team is always ready to provide fast and friendly service.
    To help our players stay in control, Big Candy Casino offers several responsible gambling
    tools that allow you to manage your gameplay safely.
    Whether you’re depositing funds, withdrawing winnings, or simply enjoying your favorite games, we ensure that every
    transaction and gameplay session is fully protected.
    But don’t just take our word for it – see what real players
    have to say about their experiences.

    References:
    https://blackcoin.co/win2aud-australia-online-casino-pokies-sports-betting/

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *