|
第2题
1,需要查看页面源代码,源代码里有说明,在冗长的非字母字符里找到字母,就是进入下一题的答案
2,因为我们神奇国度的原因,有时网络不稳定,会被G*F*W,所以使用了代理。如果不需要代理,把设置代理的语句注释掉即可
3,使用两种方式来获得结果。一种使用原生的java代码,另一种用Apache common HttpClient 的jar包(附件里)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Challenge2Search {
@SuppressWarnings("unused")
private final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static void main(String[] args) throws IOException, InterruptedException {
// set proxy
System.getProperties().setProperty("proxyHost", "127.0.0.1");
System.getProperties().setProperty("proxyPort", "8580");
URL url = new URL("http://www.pythonchallenge.com/pc/def/ocr.html");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
int i = reader.read();
StringBuilder builder = new StringBuilder();
while(i!= -1){
if((i <= 'z' && i >= 'a')||(i <= 'Z' && i >= 'A')){
builder.append((char)i);
}
i = reader.read();
}
String builderString = builder.toString();
System.out.println(" result = " + builderString.substring(builderString.indexOf("below")+5));
// close proxy
System.getProperties().setProperty("proxyHost", "");
System.getProperties().setProperty("proxyPort", "");
//HttpClient client = new HttpClient();
// set proxy
//client.getHostConfiguration().setProxy("127.0.0.1", 8580);
//GetMethod get = new GetMethod("http://www.pythonchallenge.com/pc/def/ocr.html");
//client.executeMethod(get);
//String pageInfo = get.getResponseBodyAsString();
//get.releaseConnection();
//System.out.println("result = " + getAlphabetFromString(subStr(pageInfo)));
}
public static String getAlphabetFromString(String str){
StringBuilder out = new StringBuilder();
for(int i = 0 ; i < str.length(); i++){
// int asciiChar = (int)str.charAt(i);
if(alphabet.indexOf(str.charAt(i))!=-1)
out.append(str.charAt(i));
}
return out.toString();
}
public static String subStr(String str){
String includeReturnStr = str.substring(str.lastIndexOf("<!--")+4, str.lastIndexOf("-->"));
return includeReturnStr;
}
} |
|
|