Android中 Http请求

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();
            }
        }
    } 
}

 

posted @ 2015-09-23 19:10  舞阳  阅读(149)  评论(0编辑  收藏  举报