我想從web中獲取text,我使用indexOf 和subString編寫代碼,但是不能運行。
int index = response_str.indexOf("Remote IP Address:");
index += "Remote IP Address:".length();
index += "</div><br /><div id=\"value1\">".length();
int end = response_str.indexOf("</div><br /><br />", index);
String strIP = response_str.substring(index, end);
Log.d("","Hello" + strIP );
這是示例文本,我想獲得49.156.53.152
<body>
<div id="title">Remote IP Address:</div><br /><div id="value1">**49.156.53.152**</div><br /><br />
<div id="title">UserAgent:</div><br /><div id="value2">Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11</div><br /><br />
<!-- Everyone of CCorp employees, Good luck ! --><br />
</body>
你應該把 html page 轉換成 sting,並且使用 regex / string 操作來獲取所需的數據。
try {
if(!url_text.getText().toString().trim().equalsIgnoreCase("")){
textView.setText("");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url_text.getText().toString());
// Get the response
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response_str = client.execute(request, responseHandler);
textView.setText(response_str);
}else{
Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
}
}
catch (Exception e) {
System.out.println("Some error occured.");
textView.setText(e.getMessage());
}
可能最簡單的方法是使用 sting.split 函數
String[] separated = response_str.split("**");
separated[0]; // part before the **
separated[1]; // your needed ip string
separated[2]; // part after the second **