AndroidでWebコンテンツを入手

7734 ワード

WebUtillクラス:
package com.example.ch_2013_4_11android_web;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WebUtill {
	static HttpURLConnection myHttpUrlConnection;
	static InputStream myInputStream;

	/**
	 * 
	 * @param url
	 *            address
	 * @param method
	 *            post or get
	 * @param codeType
	 *            utf-8 or other
	 * @return
	 * @throws Exception
	 */
	public static byte[] getContent(URL url, String method, String codeType)
			throws Exception {
		URL myUrl = url;

		myHttpUrlConnection = (HttpURLConnection) myUrl.openConnection();
		//       
		myHttpUrlConnection.setConnectTimeout(6000);
		// get       
		myHttpUrlConnection.setRequestMethod(method);
		//
		if (myHttpUrlConnection.getResponseCode() != 200) {
			throw new RuntimeException("Fail to request url");
		}
		byte[] result;
		//         
		myInputStream = myHttpUrlConnection.getInputStream();
		//
		result = readDate(myInputStream, "utf-8");
		myInputStream.close();
		return result;
	}

	private static byte[] readDate(InputStream input, String mode)
			throws IOException {

		byte[] buff=new byte[input.available()];

		System.out.println("input    :" + input.available());
		input.read(buff);
		return buff;
	}

	public static void closeConnection() {
		if (myHttpUrlConnection != null)
			myHttpUrlConnection.disconnect();
	}

}

MainActivity:
package com.example.ch_2013_4_11android_web;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

	

	//             
	//
	TextView myTextView = null, myTextView3 = null;
	//
	Button btn1, btn2, btn3;
	//
	ImageView myImageView;
	//
	URL myUrl;
	//
	HttpURLConnection myHttpURLConnection;
	//
	InputStream myInputStream;
	//
	String strResult = "";
	//
	ByteArrayOutputStream myByteArrayOutputStream;
	//
	
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Bundle b = msg.getData();
				String str = b.getString("value");
				myTextView3.setText(str);
			}
			if(msg.what==2){
				
			}
			if(msg.what==3){
				
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//      
		myTextView = (TextView) this.findViewById(R.id.txtInfo);
		//
		myImageView = (ImageView) this.findViewById(R.id.imageView1);
		//
		btn1 = (Button) this.findViewById(R.id.button1);
		//
		btn2 = (Button) this.findViewById(R.id.button2);
		//
		btn3 = (Button) this.findViewById(R.id.button3);
		//
		myTextView3 = (TextView) this.findViewById(R.id.mytext);
		//
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//
				new class1().start();
			}
		});
		//
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//
				new class2().start();
			}
		});
		//
	
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	class class1 extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				//
				myUrl = new URL("xxxxxxxxxxxxxx");
				//
				byte[] buff = WebUtill.getContent(myUrl, "GET", "utf-8");
				String strResult = new String(buff);
				Bundle data = new Bundle();
				data.putString("value", strResult);
				Message msg = new Message();
				msg.what = 1;
				msg.setData(data);
				handler.sendMessage(msg);
				//       
				System.out.println(strResult);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				//
				WebUtill.closeConnection();
			}
		}
	}

	//           
	class class2 extends Thread {

		@Override
		public void run() {
			//
			try {
				//
				myUrl = new URL("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif");
				//
				byte[] buff=WebUtill.getContent(myUrl, "GET", "utf-8");
				//
				final Bitmap bp = BitmapFactory.decodeByteArray(buff, 0, buff.length-1);
		        //
				handler.post(new Runnable() {
					@Override
					public void run() {
						myImageView.setImageBitmap(bp);
					}
				});
			} catch (Exception e) {
				//
				System.out.println(e.getMessage());
			}

		}

	}

	
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txtInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtInfo"
        android:text="       " />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/imageView1"
        android:text="           " />

    <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button2"
        android:text="TextView" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/mytext"
        android:text="           " />

</RelativeLayout>
AndroidManifest.xmlで
インターネット権限を追加します.