2011年12月25日日曜日

GETでホームページ取得:Android Http インターネット


package com.android.test;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;

public class AndroidTestHttpActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
  
  HttpURLConnection http = null;
  InputStream in = null;
  TextView web = (TextView) findViewById(R.id.textView1);
  try {
   // URLにHTTP接続
   URL url = new URL("http://www.google.co.jp");
   http = (HttpURLConnection) url.openConnection();
   http.setRequestMethod("GET");
   http.connect();
   // データを取得
   in = http.getInputStream();

   // HTMLソースを読み出す
   String src = new String();
   byte[] line = new byte[1024];
   int size;
   while (true) {
    size = in.read(line);
    if (size <= 0)
     break;
    src += new String(line);
   }
   // HTMLソースを表示
   web.setText(src);
  } catch (Exception e) {
   web.setText(e.toString());
  } finally {
   try {
    if (http != null)
     http.disconnect();
    if (in != null)
     in.close();
   } catch (Exception e) {
   }
  }

 }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AndroidTestHttpActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

関連記事

0 件のコメント:

コメントを投稿