import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class word08{
public static void main(String[] args) {
int year = getPublicationYear("Optimal Taxation in a Stochastic Economy: A Cobb-Douglas Example");
System.out.print(year);
if (year < 0) {
System.exit(1);
}
}
public static int getPublicationYear(String title) {
int year = -1;
try {
// Build query URL.
StringBuilder sb = new StringBuilder();
sb.append("http://www.google.co.jp/search?hl=en&q=%22");
sb.append(URLEncoder.encode(title, "UTF-8"));
sb.append("%22");
String urlString = sb.toString();
// Open HTTP connection.
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7");
conn.setRequestProperty("Referer", urlString);
conn.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader((conn.getInputStream())));
// Compile regex pattern to look for.
Pattern pattern = Pattern.compile("<span class=f>(.+?)</span>");
int openLength = "<span class=f>".length();
int closeLength = "</span>".length();
// Load content.
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
String match = matcher.group();
String yearString = match.substring(openLength,
match.length() - closeLength);
// Get publication year if possible.
try {
year = Integer.parseInt(yearString);
} catch (NumberFormatException nfe) {
continue;
}
break;
}
if (year >= 0) break;
}
conn.disconnect();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return year;
}
}
最終更新:2011年02月20日 15:01