import java.util.Hashtable;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.net.*;
import java.io.*;
public class HttpFetcher {
public static String fetch(String urlString, String id, String password, Hashtable queryTable) {
String queryString = encodeQuery(queryTable);
return fetch(urlString, id, password, queryString);
}
public static String fetch(String urlString, String id, String password, String parameter) {
StringBuffer fetchedHtmlBuffer = new StringBuffer();
URLConnection httpConnection = null;
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(urlString);
httpConnection = url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
String authInfo = id+":"+password;
String encoding = new sun.misc.BASE64Encoder().encode(authInfo.getBytes());
httpConnection.setRequestProperty ("Authorization", "Basic " + encoding);
out = new PrintWriter (httpConnection.getOutputStream());
out.print(parameter);
out.flush();
InputStream is = httpConnection.getInputStream();
in = new BufferedReader(new InputStreamReader(is),8*1024);
String line = null;
while( (line=in.readLine())!= null ) {
fetchedHtmlBuffer.append(line);
fetchedHtmlBuffer.append("\n");
}
} catch(Exception e) {
System.out.println(e.toString());
} finally {
if ( out != null ) try {out.close();}catch(Exception e){}
if ( in != null ) try {in.close();}catch(Exception e){}
}
return fetchedHtmlBuffer.toString();
}
public static String encodeQuery(java.util.Hashtable hash){
if ( hash == null ) throw new IllegalArgumentException("argument is null");
java.util.Enumeration enum = hash.keys();
StringBuffer buf = new StringBuffer();
boolean isFirst = true;
while(enum.hasMoreElements()){
if (isFirst) isFirst = false;
else buf.append('&');
String key = (String)enum.nextElement();
String value = (String)hash.get(key);
buf.append(java.net.URLEncoder.encode(key));
buf.append('=');
buf.append(java.net.URLEncoder.encode(value));
}
return buf.toString();
}
public static void main(String[] args) {
String fetchedHtml = "";
String urlString = "http://localhost/path/index.html";
String loginId = "id";
String loginPassword = "password";
String queryString = "name=myname&age=30";
fetchedHtml = fetch(urlString, loginId, loginPassword, queryString);
System.out.println(fetchedHtml);
Hashtable queryTable = new Hashtable();
queryTable.put("name","myname");
queryTable.put("age","30");
queryString = encodeQuery(queryTable);
fetchedHtml = fetch(urlString, loginId, loginPassword, queryString);
System.out.println(fetchedHtml);
}
}