码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-10-14 18:09:43      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   color   io   os   ar   sp   

bubuko.com,布布扣

 

设置权限,在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();
        }

    }

}

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

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

标签:android   style   blog   http   color   io   os   ar   sp   

原文地址:http://www.cnblogs.com/tinyphp/p/4022781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!