Pom.xml:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1</version>
</dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1</version>
</dependency>
Code:
public final String MESSAGE_URL = "http://test.com/messageservice/send";
public boolean sendMessage(Message message) {
URL url = null;
try {
url = new URL(SS_URL);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
System.out.println("Start converting message to XML.");
// Marshall
JAXBContext jaxbContext = JAXBContext.newInstance(Message.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ByteOutputStream out = new ByteOutputStream();
jaxbMarshaller.marshal(message, out);
String msg = new String(out.getBytes(),"utf-8");
System.out.println("Finish converting message to XML.");
System.out.println(msg);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setDoOutput(true);
connect.setRequestProperty("Content-Type", "text/xml");
connect.setAllowUserInteraction(false);
// send query
OutputStream os = connect.getOutputStream();
jaxbMarshaller.marshal(message, os);
os.flush();
os.close();
if (connect.getResponseCode() != 200) {
System.out.println("Message sent failed.");
return false;
}
System.out.println("Message sent.");
System.out.println("Result:");
// Unmarshall
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Message result = (N2NMessage) jaxbUnmarshaller.unmarshal(connect.getInputStream());
System.out.println("Sent Message Id: " + result.getMessageID());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
No comments:
Post a Comment