java clients

Discussions

General J2EE: java clients

  1. java clients (1 messages)

    How do a java client prepares a HTTP request and interprets a HTTP response.
  2. Re: java clients[ Go to top ]

    This is a simple program to send SOAP requests and read responses. I think you can easily understand how to do HTTP requests from this. import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class SendSoapReq { /** * System properties: * endpoint.url example - "http://localhost/MyWebApp/services/MyWebServices" * soap.action example - "my:soap:action" * request.filename - path to xml request file */ public static void main ( String[] args ) throws Exception { URL url = new URL( getProp( "endpoint.url" ) ); HttpURLConnection url_connection = (HttpURLConnection)url.openConnection(); url_connection.setRequestMethod("POST"); url_connection.setRequestProperty( "Content-Type", "text/xml; charset=utf-8" ); url_connection.setRequestProperty( "SOAPAction", "\"" + getProp( "soap.action" ) + "\"" ); url_connection.setDoOutput(true); url_connection.setDoInput( true ); // create the xml body String filename = getProp( "request.filename" ); BufferedReader reader = new BufferedReader( new FileReader ( filename ) ); StringBuffer str_buf = new StringBuffer( 1028 ); while ( reader.ready() ) { str_buf.append( reader.readLine() ); } String xml_body = str_buf.toString(); // write the request OutputStreamWriter request_writer = new OutputStreamWriter( url_connection.getOutputStream() ); request_writer.write( xml_body ); request_writer.flush(); // read the response if ( url_connection.getErrorStream() != null ) { InputStreamReader response_reader = new InputStreamReader( url_connection.getErrorStream() ); StringWriter response_writer = new StringWriter(); char[] buf = new char[4096]; int len = 0; while( response_reader.ready() ) { len = response_reader.read( buf ); response_writer.write( buf, 0, len ); } System.out.println ( response_writer.toString() ); } else { InputStreamReader response_reader = new InputStreamReader( url_connection.getInputStream() ); StringWriter response_writer = new StringWriter(); char[] buf = new char[4096]; int len = 0; while( response_reader.ready() ) { len = response_reader.read( buf ); response_writer.write( buf, 0, len ); } System.out.println ( response_writer.toString() ); System.out.println( url_connection.getHeaderFields() ); } } private static String getProp( String string ) { String prop = System.getProperty( string ); if ( prop == null ) { System.err.println( "Missing property " + string ); System.exit( 1 ); } return prop; } }