• [Android基础]Android中使用HttpURLConnection


    HttpURLConnection继承了URLConnection,因此也能够向指定站点发送GET请求、POST请求。它在URLConnetion的基础上提供了例如以下便捷的方法。

    int getResponseCode():获取server的响应代码。


    String getResponseMessage():获取server的訪问信息。
    String getRequestMethod():获取发送请求的方法。
    void setRequestMethod(String method):设置发送请求的方法。
    我们通过两个样例来体会一下:
    一、将站点的内容显示在界面上:
    1、创建一个WebView

    <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" />

    2、MainActivity.java

    public class MainActivity extends Activity {
    
        private WebView webview;
        //通过Handler在子线程更新主界面的UI
        private Handler handler = new Handler();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            webview = (WebView) findViewById(R.id.webView);
            new HttpThread("http://www.sina.com", webview, handler).start();
        }
    }
    

    3、创建一个子线程

    public class HttpThread extends Thread {
        private String url;
        private WebView webview;
        private Handler handler;
        //通过构造函数传三个參数
        public HttpThread(String url, WebView webView, Handler handler) {
            this.url = url;
            this.webview = webView;
            this.handler = handler;
        }
        }
        @Override
        public void run() {
            try {
                URL httpUri = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) httpUri.openConnection();
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");   
                final StringBuffer sb = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String str;
                while((str = reader.readLine()) != null)
                {
                    sb.append(str);
                }
                handler.post(new Runnable() {
    
                    @Override
                    public void run() {
                    //将数据载入到webview中
                        webview.loadData(sb.toString(), "text/html;charset=utf-8", null);
                    }
                });
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    4、在AndroidManifest中加入权限:
    android:name=”android.permission.INTERNET”

    二、依据URL地址下载一张图片
    1、创建一个webview

    <ImageView 
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    2、MainActivity.java

    public class MainActivity extends Activity {
    
        private Handler handler = new Handler();
        private ImageView imageView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            imageView = (ImageView) findViewById(R.id.imageView1);
            new     HttpThread("http://img5.duitang.com/uploads/item/201410/23/20141023211631_VKmfz.jpeg", imageView, handler).start();
        }

    3、创建一个子线程

    
    
    public class HttpThread extends Thread {
        private String url;
        private Handler handler;
        private ImageView imageView;
        public HttpThread(String url, ImageView imageView, Handler handler) {
            this.url = url;
            this.imageView = imageView;
            this.handler = handler;
        }
        @Override
        public void run() {
            try {
                URL httpUri = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) httpUri.openConnection();
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                //设置能够读取到输入流
                conn.setDoInput(true);
                InputStream in = conn.getInputStream();
                FileOutputStream out = null;
                String fileName = String.valueOf(System.currentTimeMillis());
                File downloadFile = null;
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                {
                    //获得SDcard的文件夹文件
                    File parent = Environment.getExternalStorageDirectory();
                    downloadFile = new File(parent, fileName);
                    out = new FileOutputStream(downloadFile);
                }
                //缓冲区
                byte[] b = new byte[2 * 1024];
                int len;
                if(out != null)
                {
                    while((len = in.read(b)) != -1)
                    {
                        out.write(b, 0, len);
                    }
                }
                final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
                handler.post(new Runnable() {
    
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    

    4、在AndroidManifest中加入权限:
    android:name=”android.permission.WRITE_EXTERNAL_STORAGE”

    这样下载的图片就显示在界面上了。

  • 相关阅读:
    Qt内存回收机制
    Qt坐标系统
    Qt信号与槽的使用
    Qt初始化代码基本说明
    Qt下载、安装及环境搭建
    搭建CentOs7的WebServer
    Laying out a webpage is easy with flex
    Let's write a framework.
    使用go语言开发一个后端gin框架的web项目
    个人总结的J2EE目前知道的涵盖面,从大方向入手,多写单元测试,加强基础
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7244346.html
Copyright © 2020-2023  润新知