2 csh 34 csh_34 于 2013.06.18 15:00 提问

从 web 页中获取 text

我想从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>

2个回答

curie_87
curie_87   2013.06.19 10:41
已采纳

你应该把 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 **
Jave_
Jave_   2013.06.18 15:46

测试可以运行,得到结果:**49.156.53.152**

Csdn user default icon
上传中...
上传图片
插入图片