Android4.0.4编程日记(5)--URL网络链接获取数据

package com.example.test;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.pojo.Params;

/**
 * 
 * @author 王莹 URL   HttpURLConnection */
public class MainActivity extends Activity {
	private ListView mylistview;

	private TextView textView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client);
		try {
	        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
			getHttp();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getHttp() {

		try {
			URL url = new URL("http://www.google.cn/");
//			URL url = new URL("http://192.168.0.133:8888/AndroidTest/login.jsp");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(10000);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("accept", "*/*");
			String location = conn.getRequestProperty("location");
			int resCode = conn.getResponseCode();
			conn.connect();
			InputStream stream = conn.getInputStream();
			byte[] data = new byte[102400];
			int length = stream.read(data);
			String str = new String(data, 0, length);
			conn.disconnect();
	        textView=(TextView) findViewById(R.id.httpnote);
			textView.setText(str);
			stream.close();
			
		} catch (Exception ee) {
			System.out.print("ee:" + ee.getMessage());
		}

	}

	/**
	 * 异常解决android.os.NetworkOnMainThreadException
	 * http://www.cnblogs.com/sjrhero/articles/2606833.html
	 */




}

顺带一提,那个AndroidManifest.xml中别忘记

你可能感兴趣的:(android)