You are here: Home > Download > Java code > Post XML

Post XML (with java code)

    (get sources)
This is a sample application that demonstrates how to send a message through TeleMessage's xml interface
from your java code.
The application posts *XML file (that represent a message) located on your local disk to our servers and get response about the sent message.
The response includes message-id and message-key for tracing message delivery.
Note: the following 3rd party packages are required: Apache's HTTPClient 2 and JavaMail.

  import java.io.*;
import java.io.FileInputStream;
import javax.mail.internet.MimeUtility;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;


  public static void main(String[] args) {
  try {
  // Get target URL
String strURL = "http://xml.telemessage.com/partners/xmlMessage.jsp";
InputStream xmlin =null;

*//Send xml file (read a local xml file and send it)
String strXMLFilename = "add your file path here" ;
File input = new File(strXMLFilename);
xmlin = new FileInputStream(input);

//Prepare HTTP post
PostMethod post = new PostMethod(strURL);

//Request content will be retrieved directly
/// from the input stream

post.setRequestBody(xmlin);

//Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// = content length is explicitly specified
// = chunk-encoding is used

if (input.length() < Integer.MAX_VALUE) {
post.setRequestContentLength((int)input.length());
} else {
post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
}

//Specify content type and encoding
// If content encoding is not explicitly specified
// ISO-8859-1 is assumed

post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

//Get HTTP client
HttpClient httpclient = new HttpClient();

//Execute request
int result = httpclient.executeMethod(post);

//Display status code
System.out.println("Response status code: " + result);

//Display response
String responseStr = post.getResponseBodyAsString();
System.out.println("Response body: ");
System.out.println(responseStr);

//Release current connection to the connection pool once you are done
post.releaseConnection();
 
} catch (Exception e) {
  System.out.println(e.getMessage());
       }
  }
Get source file
* You can enter your string directly (instead of reading the file from your local disk)
   just replace the 3 lines under 'Send xml file' section to:

String input = "add your string here";
xmlin = new ByteArrayInputStream(input.getBytes());