URLConnection &HttpURLConnection 网络请求

来源:互联网 发布:身份证图像识别 java 编辑:程序博客网 时间:2024/05/17 22:43

基本使用方法

URLConnection

访问网络的文本数据打印下载

 try {            //创建URL对象参数为网络信息地址            URL url = new URL("https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/plugins/every_cookie_a70bc15.js");            //使用URL对象获取URLConnection对象            URLConnection connection = url.openConnection();            //设置连接超时时间            connection.setConnectTimeout(1000 * 8);            //设置读取超时时间            connection.setReadTimeout(1000 * 8);            //获取输入流            InputStream inputStream = connection.getInputStream();            //字节数组输出流用于保存数据            ByteArrayOutputStream baos = new ByteArrayOutputStream();            //读取长度变量            int len = 0;            //换成数组            byte[] buf = new byte[1024 * 8];            //循环读取            while ((len = inputStream.read(buf)) != -1) {                //写入字节数组                baos.write(buf, 0, len);            }            //打印下载数据            System.out.println(baos.toString());            //创建文件            File file = new File("data.txt");            //判断文件是否存在            if (!file.exists()) {                //不存在创建                file.createNewFile();            }            //文本写入对象            FileWriter fw = new FileWriter(file);            //写入            fw.write(baos.toString());            //刷新            fw.flush();            //关闭            fw.close();        } catch (Exception e) {            e.printStackTrace();        }

访问网络图片下载

 try {            //创建URL对象 参数为网络图片地址            URL url = new URL("http://scimg.jb51.net/allimg/160805/103-160P5094351J6.jpg");            //使用URL对象获取URLConnection对象            URLConnection connection = url.openConnection();            //设置连接超时时间            connection.setConnectTimeout(1000 * 8);            //设置读取超时时间            connection.setReadTimeout(1000 * 8);            //获取输入流            InputStream inputStream = connection.getInputStream();            int len = 0;            //缓冲数组            byte[] buf = new byte[1024 * 8];            //创建文件对象            File file = new File("1.jpg");            //判断文件是否存在            if (!file.exists()) {                //如果不存在则创建文件                file.createNewFile();            }            //文件输出流            FileOutputStream fos = new FileOutputStream("1.jpg");            while ((len = inputStream.read(buf)) != -1) {                //写入文件流                fos.write(buf, 0, len);                //刷新流                fos.flush();            }            //关闭流            fos.close();        } catch (Exception e) {            e.printStackTrace();        }

HttpURLConnection

使用方法基本与URLConnection相同

请求文本信息

   try {            //穿件URL对象 参数为网络信息地址            URL url = new URL("https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/plugins/every_cookie_a70bc15.js");            //使用URL的openConnection获取HttpURLConnection 需要强转            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            //设置请求方式 GET POST 都可以            connection.setRequestMethod("GET");            //设置连接超时时间            connection.setConnectTimeout(1000 * 8);            //设置读取超时时间            connection.setReadTimeout(1000 * 8);            //获取请求返回码            int responseCode = connection.getResponseCode();            //根据返回的结果码判断是否请求成功            if (responseCode == 200) {                //请求成功                InputStream inputStream = connection.getInputStream();                //临时读取数据                String str = "";                //保存数据                String data = "";                //读取请求的信息                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));                //循环读取                while ((str = br.readLine()) != null) {                    //保存数据                    data += str;                }                //打印读取数据                System.out.println(data);            } else {                //请求失败                System.out.println("Error" + responseCode);            }        } catch (Exception e) {            e.printStackTrace();        }

请求图片

  try {            //创建URL对象 参数网络图片            URL url = new URL("http://www.bz55.com/uploads1/allimg/120519/1_120519144644_5.jpg");            //获取HttpURLConnection 对象            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            //设置连接超时时间            connection.setConnectTimeout(1000 * 8);            //设置读取超时间            connection.setReadTimeout(1000 * 8);            //设置请求方式            connection.setRequestMethod("GET");            //回去请求返回码            int responseCode = connection.getResponseCode();            //判断返回码            if (responseCode == 200) {                //请求成功                InputStream inputStream = connection.getInputStream();                //文件输出流                FileOutputStream fos = new FileOutputStream("12.jpg");                int len = 0;                //缓冲数组                byte[] buf = new byte[1024 * 8];                //循环读取                while ((len = inputStream.read(buf)) != -1) {                    //写入                    fos.write(buf, 0, len);                    //刷新流                    fos.flush();                }                //关闭流                fos.close();            } else {                //请求失败                System.err.println("Error " + responseCode);            }        } catch (Exception e) {            e.printStackTrace();        }

Android 使用

(注意)在Android中不能再主线程中操作,否则NetworkOnMainThreadException
这里写图片描述

所以在Android 中要在子线程中做网络请求操作
在AndroidManifest.xml中声明

    <uses-permission android:name="android.permission.INTERNET"/>

否则会java.lang.SecurityException
这里写图片描述

代码

  //创建一个线程        new Thread(new Runnable() {            @Override            public void run() {                try {                    //创建URL对象                    URL url = new URL("http://www.bz55.com/uploads1/allimg/120519/1_120519144644_5.jpg");                    //获取HttpURLConnection                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();                    //设置请求超时时间                    connection.setConnectTimeout(1000 * 8);                    //设置请求方式                    connection.setRequestMethod("GET");                    //回去请求返回码                    int responseCode = connection.getResponseCode();                    //判断是否请求成功                    if (responseCode == 200) {                        //获取流                        InputStream inputStream = connection.getInputStream();                    }                } catch (Exception e) {                    e.printStackTrace();                }            }        }).start();