我需要从android上的网页获取变量值。现在我有我需要的行,但是使用变量名(pfname,plname)而不是它们的值。代码如下,学校从网站上删除:
public void getJSON(View view) throws IOException {
Intent intent = new Intent(this, DisplayMessageActivity.class);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
JSONObject input = readRateMyProfessor();
try {
Log.i("JSON", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
intent.putExtra(EXTRA_MESSAGE, String.valueOf(input));
startActivity(intent);
}
public JSONObject readRateMyProfessor() throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.ratemyprofessors.com");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e1) {
e1.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
inputStream = entity.getContent();
} catch (IOException e1) {
e1.printStackTrace();
}
// json is UTF-8 by default
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String line = null;
while ((line = reader.readLine()) != null) {
if (line.contains("<li>")) {
if (!line.contains("http") || !line.contains("about") || !line.contains("blog") || !line.contains("help")
|| !line.contains("Contact") || !line.contains("TermsOfUse")) {
if ((line = reader.readLine()).contains("ShowRatings"))
while (!(line = reader.readLine()).contains("</a>")) {
if (line.contains("name")) {
String[] parts = line.split(">");
String[] parts2 = parts[1].split("<");
name = parts2[0];
} else if (line.contains("rating")) {
String[] parts = line.split(">");
String[] parts2 = parts[1].split("<");
rating = Integer.valueOf(parts2[0]);
}
json = new JSONObject();
json.put(name, rating);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
return json;
}
编辑:
我得到的一些示例输出:
http://i.imgur.com/0OpBYgM.png
然后为学校的每位教授重复这一点。我不关心我得到的多余,我可以减少那个