Android:简单联网获取网页代码

设置权限,在AndroidManifest.xml加入

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

public class MainActivity extends Activity {    private EditText address;    private Button getbutton;    private TextView text;            @Override    protected void onCreate(Bundle savedInstanceState) {        //版本4.0后需加这个,不然就报错android.os.NetworkOnMainThreadException        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()                .detectDiskReads().detectDiskWrites().detectNetwork()                .penaltyLog().build());        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()                .penaltyLog().penaltyDeath().build());        //        super.onCreate(savedInstanceState);        setContentView(R.layout.test);        //初始化        address = (EditText) findViewById(R.id.address);        getbutton = (Button) findViewById(R.id.getbutton);        text = (TextView) findViewById(R.id.text);                                    getbutton.setOnClickListener(new Button.OnClickListener() {                        @Override            public void onClick(View v) {                // TODO Auto-generated method stub                String url = address.getText().toString();                getPDAServerData(url);            }        });    }    public void getPDAServerData(String url) {        HttpClient client = new DefaultHttpClient();        HttpPost request;        try {                        request = new HttpPost(url);                        //调用HttpClient对象的execute(HttpUriRequest request)发送请求,返回一个HttpResponse            HttpResponse response = client.execute(request);                        //返回响应码为200            if (response.getStatusLine().getStatusCode() == 200) {                                //从响应中获取消息实体                HttpEntity entity = response.getEntity();                if (entity != null) {                    String out = EntityUtils.toString(entity);                    text.setText(out);                }            }                                } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

实例下载>>>>>>>>>

更多相关文章

  1. 【Android开发学习01】与Android实体设备的连接
  2. android webkit 初始化流程
  3. Android Initialization Process ---- Android 初始化过程
  4. android kernel 初始化 1
  5. Android 5.0 Input初始化

随机推荐

  1. Android下intent的setdata、settype和set
  2. Android中ImageButton自定义按钮的按下效
  3. 朝花夕拾----新组件的学习和使用
  4. Android(安卓)零碎
  5. android.intent.action.MAIN 与 android.
  6. Android-Jni线程(一)— 创建线程
  7. Android获取所在地城市名
  8. Android一些比较好的网站
  9. 更改Android模拟器中的hosts文件
  10. Android数字签名获取证书指纹(SHA1)