Java tutorial
//package com.java2s; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; public class Main { /** * This method is used to send a XML request file to web server to process the request and return * xml response containing event id. */ public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception { System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server ......."); InputStream in = null; BufferedReader bufferedReader = null; OutputStream out = null; PrintWriter printWriter = null; StringBuffer responseMessageBuffer = new StringBuffer(""); try { URL url = new URL(postUrl); URLConnection con = url.openConnection(); // Prepare for both input and output con.setDoInput(true); con.setDoOutput(true); // Turn off caching con.setUseCaches(false); con.setRequestProperty("Content-Type", "text/xml"); con.setReadTimeout(readTimeout); out = con.getOutputStream(); // Write the arguments as post data printWriter = new PrintWriter(out); printWriter.println(xml); printWriter.flush(); //Process response and return back to caller function in = con.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(in)); String tempStr = null; int tempClearResponseMessageBufferCounter = 0; while ((tempStr = bufferedReader.readLine()) != null) { tempClearResponseMessageBufferCounter++; //clear the buffer for the first time if (tempClearResponseMessageBufferCounter == 1) responseMessageBuffer.setLength(0); responseMessageBuffer.append(tempStr); } } catch (Exception ex) { throw ex; } finally { System.out.println("Calling finally in POSTXML"); try { if (in != null) in.close(); } catch (Exception eex) { System.out.println("COULD NOT Close Input Stream in try"); } try { if (out != null) out.close(); } catch (Exception eex) { System.out.println("COULD NOT Close Output Stream in try"); } } System.out.println("XMLUtils.postXMLWithTimeout: end ......."); return responseMessageBuffer.toString(); } }