package jtp.iw; import java.io.*; import java.net.*; public class GetURLContents { public static String exec(String _uri) throws IOException, MalformedURLException { return GetURLContents.exec(new URL(_uri)); } public static String exec(URL u) throws IOException { URLConnection conn = u.openConnection(); Object resp = conn.getContent(); String ct = conn.getContentType(); InputStream body = (InputStream) resp; InputStreamReader isr = new InputStreamReader(body); LineNumberReader lr = new LineNumberReader(isr); StringBuffer ret = new StringBuffer(); while(true) { String line = lr.readLine(); //System.out.println("Line:" + line); if(line == null) { break; } ret.append(line); } return ret.toString(); } /* Post the (text) data in request to the given url, and return the body of text from the server's reply. Inputs: The remote server's URL The request to POST to it The content type to use Outputs: None Returns: The body of text from the server, or NULL if the request failed */ public static String Post(String url, String request, String contentType) { try { URL u = new URL(url); URLConnection conn = u.openConnection(); conn.setDoOutput(true); byte req[] = request.getBytes(); conn.setRequestProperty("Content-length", Integer.toString(req.length)); conn.setRequestProperty("Content-type", contentType); OutputStream os = conn.getOutputStream(); os.write(req); Object resp = conn.getContent(); String ct = conn.getContentType(); InputStream body = (InputStream) resp; InputStreamReader isr = new InputStreamReader(body); LineNumberReader lr = new LineNumberReader(isr); StringBuffer ret = new StringBuffer(); while(true) { String line = lr.readLine(); if(line == null) { break; } ret.append(line); ret.append("\n"); } return ret.toString(); } catch(Exception e) { //System.out.println("failed to connect to " + url, e); return null; } } } /* END of GetURLContents */