【问题标题】:Save a Site's HTML code into string Android将站点的 HTML 代码保存到字符串 Android 中
【发布时间】:2014-01-15 12:45:52
【问题描述】:

所以我一直在尝试将网站的代码(该网站仅包含 html/php)保存到 android 内部的字符串中。

现在,我尝试了 ASyncTask,但无法让它工作。我已经阅读了整部纪录片..

我不得不承认,我是 Android 的初学者。 尽管如此,出于某种原因,我尝试过的所有操作都导致它崩溃或不起作用。

现在,我问你一个简单的例子,如何获取网站的代码,并将其设置为字符串。

提前致谢!

编辑:

MainTabView.java

package com.example.projectnova;


import java.net.URL;

import com.example.projectnova.R.string;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;

public class MainTabView extends Activity implements OnClickListener{

    TabHost th;
    TabSpec specs;
    Button search;
    EditText searchText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_tab_view);

        search = (Button)findViewById(R.id.searchButton);
        searchText = (EditText)findViewById(R.id.searchInputText);
        th = (TabHost)findViewById(R.id.tabhost);
        search.setOnClickListener(this);


         th.setup();

            specs = th.newTabSpec("tag1");
            specs.setContent(R.id.Search);

            specs.setIndicator("Search");
            th.addTab(specs);

            specs = th.newTabSpec("tag2");
            specs.setContent(R.id.Download);
            specs.setIndicator("Downloads");
            th.addTab(specs);


          /*
           * 
           * Example in (I believe)PHP 
           * 
            function streaminfo($file,$port) { 
            global $src;
            $fp = @fsockopen ($file, $port, &$errno, &$errstr, 5);
            if (!$fp) {
            echo "Could not connect to <b>{$file}:{$port}</b> ({$errno}) - {$errstr}\n";
            } else {
            fputs ($fp, "GET /7 HTTP/1.1\r\nUser-Agent:Mozilla\r\n\r\n");
            while (!feof($fp)) {
            $stream = fgets($fp,1024);
            }
            list(,$stream) = explode("<body>",$stream);
            list($stream) = explode("</body>",$stream);
            list($user, $status, $user_peak, $user_max,$filler ,$bitrate, $song) = explode(",",$stream);
            if($status== 0 ) {
            } else {
            $arr = array('nameofsong' => $song);
            echo json_encode($arr);
            }
            fclose($fp);
            }
            }
            streaminfo("188.138.79.175",8030);
          */
    }
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch(arg0.getId()){
        case R.id.searchButton:
            int i = searchText.getText().toString().length();

            if(i == 0){
                Context context = getApplicationContext();
                CharSequence text =("The search box is empty");
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
            else{

                String s = searchText.getText().toString();
                String htmlText = s.replace(" ","_"); // Works
                String link = "WebsiteUrl.com/" + htmlText + ".html"; //Works
                // searchText.setText(link); Test Purposes
            }

        }
    }

    private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
         protected Long doInBackground(URL... urls) {
             int count = urls.length;
             long totalSize = 0;
             for (int i = 0; i < count; i++) {
                 totalSize += Downloader.downloadFile(urls[i]);
                 publishProgress((int) ((i / (float) count) * 100));
                 // Escape early if cancel() is called
                 if (isCancelled()) break;
             }
             return totalSize;
         }

         protected void onProgressUpdate(Integer... progress) {
             setProgressPercent(progress[0]);
         }

         protected void onPostExecute(Long result) {
             showDialog("Downloaded " + result + " bytes");
         }
     }
}

【问题讨论】:

  • 我们在这里没有提供完整的工作示例来解决问题,但是如果您展示了您尝试过的代码,我们可以指出您出错的地方以便我们修复它
  • @RGraham 好的,请稍等片刻。
  • @Paramone 在你的代码中你从不调用 DownloadFilesTask,我认为这是问题所在

标签: android html parsing android-asynctask


【解决方案1】:

我能问一下你为什么需要这样做吗?

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

【讨论】:

  • 这不起作用,因为它会尝试从主线程访问网络
  • O.o 不是 Android 上使用 AsyncTask 或其他东西在后台进行下载的模式吗?
  • 来自 OP:“现在,我尝试了 AsyncTask,但无法让它工作”。所以如果他不能让它工作,这个答案将无济于事
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多