我试图通过使用网站“http://www.gpeters.com/names/baby-names.php”来查找名称的性别。我能够使用get请求传递参数并获取html页面作为响应,如下所示
URL url = new URL(
"http://www.gpeters.com/names/baby-names.php?name=sarah");
HttpURLConnection connection = null;
try {
// Create connection
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// Get Response
InputStream is = connection.getInputStream();
int status = connection.getResponseCode();
//System.out.println(status);
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();
//program prints whole HTML page as response.
HTML响应有一个元素,如“这是一个女孩!”,其中所需的结果位于此。如何仅提取上述字符串并打印输入参数是男孩还是女孩。示例:莎拉是个女孩..