Manifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
*******************************************
main.java
public class URLActivity extends Activity {
/** Called when the activity is first created. */
TextView mTextView = null;
ScrollView mScrollView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
mTextView = new TextView (this); //初始化textView
mScrollView = new ScrollView(this);
URLConnection conn = null;
BufferedInputStream bis = null;
ByteArrayBuffer baf = null;
try{
URL myURL = new URL ("http://www.google.com.tw/"); //初始化URL
conn = myURL.openConnection(); //打開連接
bis = new BufferedInputStream(conn.getInputStream()); //透過連接得到輸入串流
int current = 0;
baf = new ByteArrayBuffer(1000);
while ((current = bis.read()) != -1) {
baf.append((char) current); //將收到的資訊新增到ByteArrayBuffer中
}
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
mTextView.setText(EncodingUtils.getString(baf.toByteArray(), "UTF-8"));
mScrollView.addView(mTextView);//將textView新增到scrollView中
this.setContentView(mScrollView);//設定當前顯示的使用者介面為scrollView
}// end of onCreate()
}
沒有留言:
張貼留言