我正在尝试在我的库中为Volley的使用创建一个示例,并且字符串请求部分似乎无法正常工作。代码很简单,我找不到解决方法,为什么当我使用URL在线请求字符串时,它还包括HTML标签以及它来自的网站。
如何在没有HTML的情况下只提取文字?
// <<<<<<<<<<<STRING REQUEST>>>>>>>>
// #1: A string from a URL.
String url ="http://httpbin.org/html";
final TextView mTextView = (TextView) findViewById(R.id.stringView);
// #2: Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 300 characters of the response string.
mTextView.setText(response.substring(0,300));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// #3: Add the request to the RequestQueue.
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
我在TextView
内显示字符串,它应如下所示:
Herman Melville - Moby-Dick
利用现在温和,夏天凉爽的天气 这些纬度,并为特殊活跃的追求做准备 不久之后,珀斯,乞求,起水泡的老人 铁匠,还没把他的便携式锻造机再次拆下来, 在结束他对亚哈的腿的贡献工作后,但仍然 保留在甲板上,由前桅快速猛击到环形弹簧;存在 现在几乎不停地被刽子手和harpooneers,和 弓箭手为他们做一些小工作;改变,修复或新的 塑造各种武器和船用家具....
相反它看起来像这样:
<!DOCTYPE html> <html> <head> </head> <body>
<h1>Herman Melville - Moby-Dick</h1>
<div>
<p>
Availing himself of the mild, summer-cool weather that now reigned in these latitudes, and in preparation for the peculiarly active pursuits shortly to be anticipated, Perth, the begrimed, blistered old blacksmith, had not removed his portable forge to the hold again, after concluding his contributory work for Ahab's leg, but still retained it on deck, fast lashed to ringbolts by the foremast; being now almost incessantly invoked by the headsmen, and harpooneers, and bowsmen to do some little job for them; altering, or repairing, or new shaping their various weapons and boat furniture....
</p>
</div>
</body>
</html>
答案 0 :(得分:2)
看起来Volley没有完全将StringRequest变成你可能认为的String格式。所以我们必须自己解析HTML。这可以使用Jsoup完成,只需很少的代码。
要将其添加到Android Studio中,请打开模块设置,然后选择&#34; +&#34;在左上方签名,然后选择&#34;导入.JAR / .AAR包&#34;,然后从文件系统中选择您的jar下载。
请务必将compile 'org.jsoup:jsoup:1.8.3'
添加到build.gradle文件中。
修改后的代码如下:
// <<<<<<<<<<<STRING REQUEST>>>>>>>>
// #1: A string from a URL.
String url ="http://httpbin.org/html";
final TextView mTextView = (TextView) findViewById(R.id.stringView);
// #2: Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Use Jsoup to parse HTML
Document doc = Jsoup.parse(response);
String parsedText = doc.body().text();
// Display the first 300 characters of the response string.
mTextView.setText(parsedText.substring(0,300));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});