読者です 読者をやめる 読者になる 読者になる

Jsoupを使ってGETリクエストの結果を適当に表示するサンプル

使われていないコードが結構混ざってるけど...

package hoge.android;

import java.io.*;
import java.net.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class MainActivity extends Activity
{
    
    public TextView textView;
    public EditText edtInch;
    public Button btn;
    public TextView txtResult;
    public String data;
    public getHtml task;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
        
        textView = new TextView(this);
        
        
        
        task = new getHtml(textView, layout);
        task.execute();
    }
    
    class getHtml extends AsyncTask<String, Integer, String> {
        
        private TextView textView;
        private LinearLayout layout;
        
        public getHtml(TextView textView, LinearLayout layout){
            super();
            this.layout = layout;
            this.textView = textView;
        }
        
        @Override
        protected String doInBackground(String... params) {
            String outputs = "";
            
            try {
                Document doc = Jsoup.connect("http://suzuki.toshinari.jp/").get();
                Elements links = doc.select("a[href]");
                
                for(Element link: links){
                    outputs += link;
                }
                
            } catch (IOException ex) {
                Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            return outputs;
        }

        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
            layout.addView(textView);
        }
    }
}