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

Android中 Http请求

时间:2015-09-23 20:57:37      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

HttpClient

 

public class MainActivity extends Activity {

    private Button button;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = (Button)findViewById(R.id.buttonId);
        
        ButtonListener listener = new ButtonListener();
        button.setOnClickListener(listener);
    }

    class ButtonListener implements OnClickListener{

        @Override
        public void onClick(View view) {
            //原则:在主线程当中不能够访问网络
            NetworkThread nt = new NetworkThread();
            nt.start();
        }        
    }    
    class NetworkThread extends Thread{
        @Override
        public void run(){
            //创建HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            //创建代表请求的对象,参数是访问的服务器地址
            //http://www.baidu.com
            HttpGet httpGet = new HttpGet("http://www.marschen.com/data1.html");
            //执行请求,获取服务器发还的相应对象
            try {
                HttpResponse resp = httpClient.execute(httpGet);
                //检查相应的状态是否正常。检查状态码的值是否等于200
                int code = resp.getStatusLine().getStatusCode();
                if(code == 200){
                    //从相应对象当中取出数据
                    HttpEntity entity = resp.getEntity();
                    InputStream in = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String line = reader.readLine();
                    Log.d("HTTP", "从服务器取得的数据位:" + line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } 
}

 

Android中 Http请求

标签:

原文地址:http://www.cnblogs.com/wuyong0818/p/4803986.html

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