我想从静态博客页面下载html,以便获取相关数据并使用它。对于异步程序,我正在使用robospice library。
事实是,使用SimpleTextRequest我只得到html的第一行,即
<?xml version="1.0" encoding="UTF-8"?>
我应该使用哪个请求来下载整个html源代码?我没有在样品中发现任何类似的东西。谷歌搜索“robospice”主要导致他们的源代码,似乎这个库的教程很少。
更新:受到第一个答案的启发,我创建了这个自定义spicerequest:
public class HtmlRequest extends SpiceRequest<String> {
private static String reqUrl;
public HtmlRequest(String url) {
super(String.class);
reqUrl = url;
aLog.d("HtmlRequest.HtmlRequest url : " + url);
}
@Override
public String loadDataFromNetwork() throws Exception {
String html = "";
HttpClient httpClient = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
HttpGet get = new HttpGet(reqUrl);
HttpResponse response = httpClient.execute(get);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
aLog.d("HtmlRequest.loadDataFromNetwork statusCode : " + statusCode);
if (statusCode == 200) {
/*
* Si todo fue ok, montamos la String con el HTML
*/
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
aLog.d("HtmlRequest.loadDataFromNetwork line : " + line);
builder.append(line);
}
html = builder.toString();
aLog.d("HtmlRequest.loadDataFromNetwork html : " + html);
}
httpClient.getConnectionManager().shutdown();
return html;
}
}
然后,在我的活动上我有
spiceManager.execute(htmlRequest, "text", DurationInMillis.NEVER, new StaticItemRequestListener());
然而,除了构造函数方法中的那个之外,我没有得到我在自定义请求中设置的日志。
事情是:虽然我的htmlRequest显然没有被执行,但我仍然得到上面的xml标题。我一定做错了,但我却无法看到它......
答案 0 :(得分:2)
很奇怪你得到的是xml文件的标题而不是html。 尝试向服务器询问html版本:
public class ExampleRequest extends SpiceRequest<String> {
public ExampleRequest() {
super(String.class);
}
@Override
public String loadDataFromNetwork() throws Exception {
String url = "your website url";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url)
.openConnection();
urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
urlConnection.setRequestProperty("Content-Type", "text/html");
String result = IOUtils.toString(urlConnection.getInputStream());
urlConnection.disconnect();
return result;
}
}