Http之客户端请求服务器,服务器响应客户端。通过Handler在主线程中读取数据

Http协议
客户端请求服务器,服务器响应客户端
步骤
1、
生成代表客户端的HttpClient对象
2、生成代表请求的HttpGet对象
3、发送请求,获得 服务器返回的HttpResponse对象
4、判断响应状态是否正常
5、获得相应对象中的数据
/**  * 子线程Http访问服务器,取得返回的数据  * 通过Handler,主线程读取数据  */ public class HttpActivity extends Activity {
    private Button button;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new MyOnclick());
        handler = new MyHandler();
    }

    class MyOnclick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            //主线程当中不许访问网络
            WorkThread workThread = new WorkThread();
            workThread.start();
        }
    }

    class WorkThread extends Thread {

        @Override
        public void run() {
            //生成代表客户端的HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();
            //生成代表请求的HttpGet对象
            HttpGet httpGet = new HttpGet("http://www.marschen.com/data1.html");
            try {
                //发送请求,获得 服务器返回的HttpResponse对象
                HttpResponse httpResponse = httpClient.execute(httpGet);
                int code = httpResponse.getStatusLine().getStatusCode();
                //code等于200,说明响应状态正常
                if (code == 200) {
                    //获得相应对象中的数据
                    HttpEntity httpEntity = httpResponse.getEntity();
                    InputStream inputStream = httpEntity.getContent();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String s = bufferedReader.readLine();
                    //将读出的服务器数据放到message的对象中去
                    //使用sendMessage()发送数据
                    Message message = new Message();
                    message.obj = s;
                    handler.sendMessage(message);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            //msg中的对象读取出来
            String s = (String) msg.obj;
            Toast.makeText(HttpActivity.this, "输出的数据为" + s, Toast.LENGTH_SHORT).show();
        }
    }
}

你可能感兴趣的:(Http之客户端请求服务器,服务器响应客户端。通过Handler在主线程中读取数据)