将网站的HTML代码保存到字符串Android中

时间:2014-01-15 12:45:53

标签: android html parsing android-asynctask

所以我一直在尝试将网站的代码保存(这个网站只包含html / php),进入android内部的一个String。

现在,我已经尝试过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");
         }
     }
}

1 个答案:

答案 0 :(得分:0)

我可以问你为什么要这样做吗?

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();