1

我想从静态博客页面下载 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 标头。我一定是做错了什么,但我却看不到它......

4

1 回答 1

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;
    }
}
于 2013-05-15T13:17:50.870 回答