采用HttpURLConnect替换过时的HttpClient

本文介绍了在Android中,由于HttpClient被标记为过时,如何转向使用HttpURLConnection进行网络通信的问题。通过官方文档,详细展示了从HttpClient到HttpURLConnection的转换过程,并解决了HttpURLConnection在获取内容长度时出现的问题,确保了进度条的正常显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 问题描述
    在使用org.apache.http.client.HttpClient进行网络通信的时候,as提示已经过时了。于是就查了一下说是用HttpURLConnect。就查阅了一下相关文档https://developer.android.google.cn/reference/java/net/HttpURLConnection.html
  2. 用HttpClient版本的代码(MyThread)
    private class MyThread extends Thread {
        @Override
        public void run() {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet("http://www.izhangqian.com");
                HttpResponse response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                long length = entity.getContentLength();
                InputStream inputStream = entity.getContent();
                int n = -1;
                int count = 0;
                byte[] bytes = new byte[128];
                StringBuffer result = new StringBuffer();
                while ((n = inputStream.read(bytes)) != -1) {
                    result.append(new String (bytes, 0, n));
                    count += n;

                    Looper looper = Looper.getMainLooper();
                    myHandler = new MyHandler(looper);
                    myHandler.removeMessages(1);
                    if (length > 0) {
                        Message msg = new Message();
                        int percent =(int)((count / (float)length) * 100);
                        if (percent < 100) {
                            msg.what = 1;
                            msg.obj = String.valueOf(percent);
                            //msg.obj = String.valueOf(55);
                        } else {
                            msg.what = 2;
                            msg.obj = String.valueOf(result);
                        }

                        myHandler.sendMessage(msg);
                    }

                    Thread.sleep(50);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

3. 用HttpURLConnection的版本
根据官方文档
官网文档修改为如下

   private class MyThread extends Thread {
        @Override
        public void run() {
            Looper.prepare();
            Looper looper = Looper.getMainLooper();
            myHandler = new MyHandler(looper);

            StringBuffer result = new StringBuffer();
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL("http://www.izhangqian.com");
                urlConnection = (HttpURLConnection) url.openConnection();
                //InputStream inputStream = (InputStream) urlConnection.getContent();
                InputStream inputStream = urlConnection.getInputStream();

                int length = urlConnection.getContentLength();
                int n = -1;
                int count = 0;
                byte[] bytes = new byte[128];
                while ((n = inputStream.read(bytes)) != -1) {
                    result.append(new String(bytes, 0, n));
                    count += n;

                    if (length > 0) {
                        Message msg = new Message();
                        int percent = (int) ((count / (float) length) * 100);
                        if (percent < 100) {
                            msg.what = 1;
                            msg.obj = String.valueOf(percent);
                        } else {
                            msg.what = 2;
                            msg.obj = String.valueOf(result);
                        }
                        myHandler.sendMessage(msg);
                    }
                    Thread.sleep(50);
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }
            Looper.loop();
        }
    }

4. 修正
但是实际上,会发现其实有一个问题就是那个length是-1。导致在主程序中的进度条出现了很大的问题。查阅各种资料可算明白这个原因了,这里是传送门
修改上述代码如下:

 private class MyThread extends Thread {
        @Override
        public void run() {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet("http://www.izhangqian.com");
                HttpResponse response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                long length = entity.getContentLength();
                InputStream inputStream = entity.getContent();
                int n = -1;
                int count = 0;
                byte[] bytes = new byte[128];
                StringBuffer result = new StringBuffer();
                while ((n = inputStream.read(bytes)) != -1) {
                    result.append(new String (bytes, 0, n));
                    count += n;

                    Looper looper = Looper.getMainLooper();
                    myHandler = new MyHandler(looper);
                    myHandler.removeMessages(1);
                    if (length > 0) {
                        Message msg = new Message();
                        int percent =(int)((count / (float)length) * 100);
                        if (percent < 100) {
                            msg.what = 1;
                            msg.obj = String.valueOf(percent);
                            //msg.obj = String.valueOf(55);
                        } else {
                            msg.what = 2;
                            msg.obj = String.valueOf(result);
                        }

                        myHandler.sendMessage(msg);
                    }

                    Thread.sleep(50);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值