Amigo, tenho uma classe que envia um XML para um servidor de mensageria (SMS). Não sei te dizer se existe ou não algo mais fácil que isto, sei que montei desta forma e funciona bem. rsrs
De uma olhada na minha classe:
public void enviaMensagem(String messageID, String sender, String password, int notificationRequested, int lifeTimeToSend, String message, String receivers) throws IOException, ParserConfigurationException, SAXException {
StringTokenizer strt = new StringTokenizer(receivers, "|");
int count = 0;
StringBuffer destinatarios = new StringBuffer();
while (strt.hasMoreElements()) {
String nextReceiver = (String) strt.nextElement();
if (!nextReceiver.startsWith("0")) {
nextReceiver = "0" + nextReceiver;
}
destinatarios.append(" <DM>" + nextReceiver + "</DM> ");
count++;
}
StringBuffer strb = new StringBuffer();
strb.append(" <ShortMessage ");
strb.append(" xmlns=\"Submit\" ");
strb.append(" MessageID=\"" + messageID + "\" ");
strb.append(" CountMessages=\"" + count + "\" ");
strb.append(" SenderID=\"" + sender + "\" ");
strb.append(" SenderPassword=\"" + password + "\" ");
strb.append(" NotificationRequested=\"" + notificationRequested + "\" ");
if (lifeTimeToSend > 0) {
strb.append(" LifeTimeToSend=\"" + lifeTimeToSend + "\"> ");
} else {
strb.append(">");
}
strb.append(" <TextMessage>" + message + "</TextMessage> ");
strb.append(destinatarios);
strb.append(" </ShortMessage> ");
StringBuffer retorno = postXml(URL_ENVIO_SMS, strb.toString());
// bom, aqui fazia algumas outras coisas com o retorno, mas nada que importa em sua aplicação... =p
}
private StringBuffer postXml(String strUrlString, String strXml) throws IOException, ParserConfigurationException, SAXException {
URL oUrl = new URL(strUrlString);
HttpURLConnection oHttpURLConnection = (HttpURLConnection) oUrl.openConnection();
oHttpURLConnection.setDoInput(true);
oHttpURLConnection.setDoOutput(true);
oHttpURLConnection.setUseCaches(false);
oHttpURLConnection.setRequestMethod("POST");
oHttpURLConnection.setRequestProperty("Content-Type", "text/xml");
oHttpURLConnection.connect();
OutputStream out = oHttpURLConnection.getOutputStream();
out.write(strXml.getBytes());
out.flush();
out.close();
BufferedReader oBufferedReader = new BufferedReader(new InputStreamReader(oHttpURLConnection.getInputStream()));
String strResponse = null;
StringBuffer strbResponse = new StringBuffer();
while (null != (strResponse = oBufferedReader.readLine())) {
strbResponse.append(strResponse);
}
oBufferedReader.close();
oHttpURLConnection.disconnect();
return strbResponse;
}
Espero que possa ter ajudado.
Se entendi errado, me desculpa. Explica melhor que vejo se consigo te ajudar.
[quote=Jefries]É um arquico XML mesmo que eu tenho que enviar, mas é um arquivo pronto…
Tem como você me mandar um exemplo??? :?: :?: [/quote]
Olá!
Para gerar um xml vc pode usar DOM4J ou XSTREAM que são as apis mais fáceis de se trabalhar, qualquer busca no google lhe mostra exemplos de como usá-las. Quanto a “enviar para um site”, vc está sendo um pouco genérico demais, existem N maneiras de fazer um envio de arquivo, via FTP, via http post e etc. Como vc pretende mandá-lo?
Bom, neste caso abra-o, leia-o e envie da mesma forma… rsrsrs
É de bom tom mencionar que no servidor que voce está enviando, deve ter uma interface para ler este xml. Caso contrario, voce deve fazer exatamente o que foi sugerido pelo Denis (enviar via FTP).
Seguindo a linha de que o servidor POSSUI a interface para receber o XML e tratá-lo de forma correta, segue a dica:
Exemplo:
/* Imports necessarios;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
*/
public String getXml(String caminho) {
File f = new File(caminho);
if (!f.exists()) {
return null;
}
try {
BufferedReader in = new BufferedReader(new FileReader(f));
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Implementando no restante da classe:
public void sendXML(){
String url = "URL para envio do XML";
String retorno = postXml(url, getXml("/Users/LucasIsrael/workspace/AO/src/arquivo.xml"));
System.out.println(retorno); // faz qualquer coisa com o retorno.
}
public String getXml(String caminho) {
File f = new File(caminho);
if (!f.exists()) {
return null;
}
try {
BufferedReader in = new BufferedReader(new FileReader(f));
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private StringBuffer postXml(String strUrlString, String strXml) throws IOException, ParserConfigurationException, SAXException {
URL oUrl = new URL(strUrlString);
HttpURLConnection oHttpURLConnection = (HttpURLConnection) oUrl.openConnection();
oHttpURLConnection.setDoInput(true);
oHttpURLConnection.setDoOutput(true);
oHttpURLConnection.setUseCaches(false);
oHttpURLConnection.setRequestMethod("POST");
oHttpURLConnection.setRequestProperty("Content-Type", "text/xml");
oHttpURLConnection.connect();
OutputStream out = oHttpURLConnection.getOutputStream();
out.write(strXml.getBytes());
out.flush();
out.close();
BufferedReader oBufferedReader = new BufferedReader(new InputStreamReader(oHttpURLConnection.getInputStream()));
String strResponse = null;
StringBuffer strbResponse = new StringBuffer();
while (null != (strResponse = oBufferedReader.readLine())) {
strbResponse.append(strResponse);
}
oBufferedReader.close();
oHttpURLConnection.disconnect();
return strbResponse;
}