DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Douglas has posted 12 posts at DZone. View Full User Profile

Using Java, POST A Block Of XML To A Web Server

03.03.2009
| 23315 views |
  • submit to reddit
        // This is a working example of POSTing a string (representing a block of XML) to a web server

try
{
    URL url = new URL( argUrl );
    URLConnection con = url.openConnection();

    // specify that we will send output and accept input
    con.setDoInput(true);
    con.setDoOutput(true);

    con.setConnectTimeout( 20000 );  // long timeout, but not infinite
    con.setReadTimeout( 20000 );

    con.setUseCaches (false);
    con.setDefaultUseCaches (false);

    // tell the web server what we are sending
    con.setRequestProperty ( "Content-Type", "text/xml" );

    OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
    writer.write( requestXml );
    writer.flush();
    writer.close();

    // reading the response
    InputStreamReader reader = new InputStreamReader( con.getInputStream() );

    StringBuilder buf = new StringBuilder();
    char[] cbuf = new char[ 2048 ];
    int num;

    while ( -1 != (num=reader.read( cbuf )))
    {
        buf.append( cbuf, 0, num );
    }

    String result = buf.toString();
    System.err.println( "\nResponse from server after POST:\n" + result );
}
catch( Throwable t )
{
    t.printStackTrace( System.out );
}