Java: simplify HTTP GET/POST with URLReader
October 16, 2008 20:45:40 Last update: March 28, 2011 20:23:22
Java's built-in classes are way too complex/flexible for a simple protocol like HTTP. This is a wrapper to simplify HTTP GET and POST.
A simple test:
import java.io.*; import java.net.*; import java.util.*; public class URLReader { // do not instantiate this class private URLReader() { } public static InputStream getInputStream(String urlString, Map<String, List<String>> inputHeaders, Map<String, List<String>> outputHeaders, Map<String, String> formData) throws MalformedURLException, IOException { URL url = new URL(urlString); URLConnection urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); if (inputHeaders != null) { for (String key: inputHeaders.keySet()) { List<String> values = inputHeaders.get(key); for (String value: values) { urlConn.addRequestProperty(key, value); } } } if ((formData != null) && (!formData.isEmpty())) { urlConn.setDoOutput(true); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); StringBuilder sb = new StringBuilder(); for (String name: formData.keySet()) { sb.append(URLEncoder.encode(name, "UTF-8")) .append("=") .append(URLEncoder.encode(formData.get(name), "UTF-8")) .append("&"); } DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); out.writeBytes(sb.substring(0, sb.length() - 1)); out.flush(); out.close(); } else { urlConn.setDoOutput(false); } if (outputHeaders != null) { outputHeaders.clear(); outputHeaders.putAll(urlConn.getHeaderFields()); } return urlConn.getInputStream(); } // Simple GET requests public static InputStream getInputStream(String urlString) throws MalformedURLException , IOException { return getInputStream(urlString, null, null, null); } // Simple POST. We don't care about headers. public static InputStream getInputStream(String urlString, Map<String, String> formData) throws MalformedURLException, IOException { return getInputStream(urlString, null, null, formData); } }
A simple test:
import java.io.*; import java.util.*; public class TestURLReader { public static void main(String[] args) throws Exception { Map<String, List<String>> sendHeaders = new HashMap<String, List<String>>(); sendHeaders.put("Cookie", Arrays.asList("JSESSIONID=c0a89f8022bafe6e82e9c1a340a691a18402682d39ac")); Map<String, List<String>> respHeaders = new HashMap<String, List<String>>(); BufferedReader reader = new BufferedReader( new InputStreamReader( URLReader.getInputStream("http://localhost:8080/welcome.do", sendHeaders, respHeaders, null) )); // print response headers for (String k: respHeaders.keySet()) { List<String> values = respHeaders.get(k); for (String v: values) { System.out.printf("%s: %s\n", k, v); } } // print contents of the page String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } reader.close(); } }